Html 如何使用 CSS 轻松地将 <div> 水平居中?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/618097/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 23:24:06  来源:igfitidea点击:

How do you easily horizontally center a <div> using CSS?

csshtml

提问by cmcginty

I'm trying to horizontally center a <div>block element on a page and have it set to a minimum width. What is the simplest way to do this? I want the <div>element to be inline with rest of my page. I'll try to draw an example:

我正在尝试将<div>页面上的块元素水平居中并将其设置为最小宽度。什么是最简单的方法来做到这一点?我希望该<div>元素与页面的其余部分内联。我会试着举一个例子:

page text page text page text page text
page text page text page text page text
               -------
               | div |
               -------
page text page text page text page text
page text page text page text page text

回答by Tivie

In the case of a non-fixed widthdiv (i.e. you don't know how much space the div will occupy).

非固定宽度div的情况下(即您不知道 div 将占用多少空间)。

#wrapper {
  background-color: green; /* for visualization purposes */
  text-align: center;
}
#yourdiv {
  background-color: red; /* for visualization purposes */
  display: inline-block;
}
<div id="wrapper">    
    <div id="yourdiv">Your text</div>
</div>

Keep in mind that the width of #yourdivis dynamic -> it will grow and shrink to accommodate the text inside it.

请记住,的宽度#yourdiv是动态的 -> 它会增长和缩小以适应其中的文本。

You can check browser compatibility on Caniuse

您可以在Caniuse上检查浏览器兼容性

回答by Antony Scott

In most browsers this will work:

在大多数浏览器中,这将起作用:

div.centre {
  width: 200px;
  display: block;
  background-color: #eee;
  margin-left: auto;
  margin-right: auto;
}
<div class="centre">Some Text</div>

In IE6 you will need to add another outer div:

在 IE6 中,您需要添加另一个外部div

div.layout {
  text-align: center;
}

div.centre {
  text-align: left;
  width: 200px;
  background-color: #eee;
  display: block;
  margin-left: auto;
  margin-right: auto;
}
<div class="layout">
  <div class="centre">Some Text</div>
</div>

回答by Russ Cam

margin: 0 auto;

as ck has said, min-widthis not supported by all browsers

正如ck 所说,并非所有浏览器都支持min-width

回答by Manoj Kumar

The title of the question and the content is actually different, so I will post two solutions for that using Flexbox.

问题的标题和内容实际上是不同的,所以我会发布两个使用Flexbox.

I guess Flexboxwill replace/add to the current standard solution by the time IE8 and IE9 is completely destroyed ;)

我想Flexbox将在 IE8 和 IE9 完全销毁时替换/添加到当前的标准解决方案中;)

Check the current Browser compatibility table for flexbox

检查flexbox的当前浏览器兼容性表

Single element

单个元素

.container {
  display: flex;
  justify-content: center;
}
<div class="container">
  <img src="http://placehold.it/100x100">
</div>

Multiple elements but center only one

多个元素但仅居中一个

Default behaviour is flex-direction: rowwhich will align all the child items in a single line. Setting it to flex-direction: columnwill help the lines to be stacked.

默认行为是flex-direction: row将所有子项对齐在一行中。将其设置为flex-direction: column将有助于堆叠线。

.container {
  display: flex;
  flex-direction: column;
}
.centered {
  align-self: center;
}
<div class="container">
  <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.
   </p>
  <div class="centered"><img src="http://placehold.it/100x100"></div>
  <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It
    has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. </p>
</div>

回答by wh1t3cat1k

If old browsers are not an issue, use HTML5 / CSS3. If they are, apply polyfills and still use HTML5 / CSS3. I assume that your div has no margins or paddings here, but they are relatively easy to account for. The code follows.

如果旧浏览器不成问题,请使用 HTML5/CSS3。如果是,应用 polyfills 并仍然使用 HTML5 / CSS3。我假设您的 div 在这里没有边距或填充,但它们相对容易解释。代码如下。

.centered {
    position: relative;
    left: 50%;
    transform: translateX(-50%);
}

What this does is:

它的作用是:

  1. Position the divrelative to its container;
  2. Position the div's left boundary at 50% of its container widthhorizontally;
  3. Translate back horizontally by 50% of the div's own width.
  1. div相对于其容器定位;
  2. div的左边界水平放置在其容器宽度的50% 处;
  3. div自身宽度的50% 水平平移回来。

It is easy to imagine this process to confirm that the divwould be horizontally centered eventually. As a bonus, you can center verticallyat no additional cost:

很容易想象这个过程来确认div最终会水平居中。作为奖励,您可以垂直居中而无需额外费用:

.centered-vertically {
    position: relative;
    top: 50%;
    transform: translateY(-50%);
}

The advantage of this approach is that you don't have to do any counterintuitive stuff, such as considering your div a text of sorts, wrapping it in a (often semantically useless) additional container, or giving it a fixed width, which is not always possible.

这种方法的优点是您不必做任何违反直觉的事情,例如将您的 div 视为某种文本,将其包装在(通常在语义上无用的)附加容器中,或者给它一个固定的宽度,这不是总是可能的。

Don't forget vendor prefixes for transformif needed.

transform如果需要,不要忘记供应商前缀。

回答by sjh

CSS, HTML:

CSS, HTML:

div.mydiv {width: 200px; margin: 0 auto}
<div class="mydiv">
    
    I am in the middle
    
</div>

Your diagram shows a block level element also (which a div usually is), not an inline one.

您的图表还显示了一个块级元素(通常是 div),而不是内联元素。

Of the top of my head, min-widthis supported in FF2+/Safari3+/IE7+. Can be done for IE6 using hackety CSS, or a simple bit of JS.

在我的头顶上,min-width支持 FF2+/Safari3+/IE7+。可以使用 hackety CSS 或简单的 JS 为 IE6 完成。

回答by cjk

.center {
   margin-left: auto;
   margin-right: auto;
}

Minimum width is not globally supported, but can be implemented using

最小宽度不是全局支持的,但可以使用

.divclass {
   min-width: 200px;
}

Then you can set your div to be

然后你可以将你的 div 设置为

<div class="center divclass">stuff in here</div>

回答by Joshua Pekera

You should use position: relativeand text-align: centeron the parent element and then display: inline-blockon the child element you want to center. This is a simple CSS design pattern that will work across all major browsers. Here is an example below or check out the CodePen Example.

您应该在父元素上使用position: relativetext-align: center,然后display: inline-block在要居中的子元素上使用。这是一个简单的 CSS 设计模式,适用于所有主要浏览器。这是下面的示例或查看CodePen 示例

p {
  text-align: left;
}
.container {
  position: relative;
  display: block;
  text-align: center;
}
/* Style your object */

.object {
  padding: 10px;
  color: #ffffff;
  background-color: #556270;
}
.centerthis {
  display: inline-block;
}
<div class="container">

  <p>Aeroplanigera Mi Psychopathologia Subdistinctio Chirographum Intuor Sons Superbiloquentia Os Sors Sesquiseptimus Municipatio Archipresbyteratus O Conclusio Compedagogius An Maius Septentrionarius Plas Inproportionabilit Constantinopolis Particularisticus.</p>

  <span class="object centerthis">Something Centered</span>

  <p>Aeroplanigera Mi Psychopathologia Subdistinctio Chirographum Intuor Sons Superbiloquentia Os Sors Sesquiseptimus Municipatio Archipresbyteratus O Conclusio Compedagogius.</p>
</div>

回答by RiyazAhmed

Please use the below code and your div will be in the center.

请使用以下代码,您的 div 将位于中心。

.class-name {
    display:block;
    margin:0 auto;
}

回答by Zawarudo

you can use margin: 0 autoon your css instead of margin-left: auto; margin-right: auto;

你可以margin: 0 auto在你的 css 上使用而不是margin-left: auto; margin-right: auto;