如何使用CSS轻松水平居中一个<div>?

748

我正在尝试水平居中一个页面上的 <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

我不喜欢这些答案中的任何一个。如果您不知道宽度,该怎么办?例如,它可能只是一个单词。 - RGBK
1
需要注意的是,如果宽度为100%,则对齐将不起作用。 - Amol M Kulkarni
2
我刚刚发现了一个名为webgenerator的网站:http://howtocenterincss.com/ 它可以帮你把任何想要居中的元素居中,无论你想怎样居中。 ;) - Sylhare
做这个:div.e1{text-align: center;} - monkey
22个回答

824

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

#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>

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

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


7
我已经使用“margin:0 auto”方案很长时间了,但这个更好。 - Nahn
2
@UriKlar 因为 margin: 0 auto 更容易且更语义化正确。 - bjb568
2
该解决方案使inline-block变得有用! - Erlend K.H.
1
@NathanHinchey #wrapper {text-align: center;}#yourdiv {display: inline-block;} - Tivie
7
这种方法的一个缺点是 text-align: center 属性会被继承,因此会影响内容;而 margin: 0 auto 属性则不会。 - Csati
显示剩余7条评论

578

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

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


2
是的,由于IE7之前的IE中存在布局错误,所以你必须这样做。但在IE8中,一个简单的text-align: center就足够了。 :) - Eriawan Kusumawardhono
8
这意味着IE8仍然存在问题,因为它不能正确处理文本。 - cjk
42
如果你想要这个方法起作用,就必须知道容器的宽度。如果宽度改变了,你就必须更新你的 CSS(如果内容是动态生成的,这将非常麻烦)。 - BMiner
1
我相信如果您不知道内容的宽度,它应该可以工作,但是您需要将宽度设置为某个值,因为 div 会扩展到其容器的宽度。 - Antony Scott
1
为什么我们必须指定width:200px?为什么我们要硬编码它? - Raj Pawan Gumdal
显示剩余12条评论

62

1
请注意,这仅在元素的 width 属性也设置时才起作用。当您希望元素的宽度是动态的(基于其内容),请参阅所选答案。 - Niko Bellic

50

问题的标题和内容实际上是不同的,因此我将使用Flexbox发布两个解决方案。

我猜Flexbox会在IE8和IE9完全消失之前替换/添加到当前的标准解决方案中 ;)

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

单一元素

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

多个元素但只居中一个

默认行为是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>


是的,Flexbox 是(并不是那么)“现代”的做法 :) - Tivie
没错。Tivie,你愿意编辑一下,让它能够达到普通听众的水平吗? ;) - m4n0
2
这个方法在前两个答案都没用时对我很有帮助。谢谢。 - Ellen Spertus
1
@ManojKumar 我认为flexbox解决了很多设计问题,目前几乎所有浏览器都支持它。 - Tivie
1
由于某些原因,我的Bourbon Neat项目中的margin: 0 auto无法正常工作,但是flexbox拯救了这一天。 - Halfacht
显示剩余3条评论

35

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

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

这样做的作用是:

  1. div 相对于其容器定位;
  2. 水平将 div 的左边界定位在其容器宽度的50%处;
  3. 再水平移动 div 宽度的50%

很容易想象出这个过程,以确认最终 div 会水平居中。作为奖励,您可以在无需额外成本的情况下垂直居中它:

.centered-vertically {
    position: relative;
    top: 50%;
    transform: translateY(-50%);
}
这种方法的优点是您不必执行任何反直觉的操作,例如将您的div视为某种文本,将其包装在(通常语义无关紧要的)额外容器中,或者给它一个固定的宽度,这并不总是可能的。
如果需要,请不要忘记使用transform的供应商前缀。

水平方法的一个问题是,居中的元素不会动态缩放超过父元素宽度的50%:https://jsfiddle.net/ywy9w3gk/ - user2145184

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

最小宽度并不被全局支持,但可以使用以下方式实现

.divclass {
   min-width: 200px;
}

那么你可以将你的 div 设置为:

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

28

CSS, HTML:

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

你的图示展示了一个块级元素(通常div就是块级元素),而不是行内元素。

我记得,min-width在FF2+/Safari3+/IE7+中都有支持。可以通过hackety CSS或简单的JS来支持IE6。


感谢您澄清“inline”术语的含义。我想表达的是,我不希望它浮动在任何文本上方。 - cmcginty

11
使用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>


text-align: center 就是解决方案。只需要将其添加到父元素即可。 - magnusarinell

10
请使用以下代码,您的div会居中显示。
.class-name {
    display:block;
    margin:0 auto;
}

9

您可以在CSS中使用margin: 0 auto代替margin-left: auto; margin-right: auto;


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接