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

cmc*_*nty 706 html css

我正在尝试将一个<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
Run Code Online (Sandbox Code Playgroud)

Tiv*_*vie 779

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

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

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

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

  • 这种方法的一个缺点是`text-align:center`是继承的,因此会影响内容,而margin:0 auto`则不会. (7认同)
  • 我一直在使用"margin:0 auto"解决方案很长一段时间,但这更好. (6认同)
  • @UriKlar因为margin:0 auto更容易并且在语义上更正确。 (2认同)
  • 这个解决方案使内联块有用! (2认同)

Ant*_*ott 566

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

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

在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;
}
Run Code Online (Sandbox Code Playgroud)
<div class="layout">
  <div class="centre">Some Text</div>
</div>
Run Code Online (Sandbox Code Playgroud)

  • 另外......只有在知道容器的宽度时才有效.如果宽度发生变化,则必须更新CSS(如果内容是动态生成的,则会发臭) (40认同)
  • 这意味着IE8仍然是错误的,因为它不是文本. (8认同)
  • 是的,由于IE7之前IE中的布局错误,你必须这样做.但在IE8中,一个简单的text-align:center就足够了.:) (2认同)

Rus*_*Cam 59

margin: 0 auto;
Run Code Online (Sandbox Code Playgroud)

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


Man*_*mar 41

问题的标题和内容实际上是不同的,所以我将发布两个解决方案Flexbox.

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

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

单个元素

.container {
  display: flex;
  justify-content: center;
}
Run Code Online (Sandbox Code Playgroud)
<div class="container">
  <img src="http://placehold.it/100x100">
</div>
Run Code Online (Sandbox Code Playgroud)

多个元素但只有一个中心

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

.container {
  display: flex;
  flex-direction: column;
}
.centered {
  align-self: center;
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

  • 当前两个答案没有时,这对我有用。谢谢你。 (2认同)

wh1*_*t1k 30

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

.centered {
    position: relative;
    left: 50%;
    transform: translateX(-50%);
}
Run Code Online (Sandbox Code Playgroud)

这样做是:

  1. 定位div相对于其容器的相对位置;
  2. div左边界定位在其容器宽度的 50%水平位置;
  3. 由50%的转换回水平div自身宽度.

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

.centered-vertically {
    position: relative;
    top: 50%;
    transform: translateY(-50%);
}
Run Code Online (Sandbox Code Playgroud)

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

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


sjh*_*sjh 28

CSS,HTML:

div.mydiv {width: 200px; margin: 0 auto}
Run Code Online (Sandbox Code Playgroud)
<div class="mydiv">
    
    I am in the middle
    
</div>
Run Code Online (Sandbox Code Playgroud)

您的图表也显示了块级元素(通常是div),而不是内联元素.

在我的头脑中,min-widthFF2 +/Safari3 +/IE7 +支持.可以使用hackety CSS或简单的JS来为IE6做.


cjk*_*cjk 27

.center {
   margin-left: auto;
   margin-right: auto;
}
Run Code Online (Sandbox Code Playgroud)

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

.divclass {
   min-width: 200px;
}
Run Code Online (Sandbox Code Playgroud)

然后你可以设置你的div

<div class="center divclass">stuff in here</div>
Run Code Online (Sandbox Code Playgroud)


Jos*_*era 11

您应该在父元素上使用position: relativeand text-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;
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)


小智 10

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

.class-name {
    display:block;
    margin:0 auto;
}
Run Code Online (Sandbox Code Playgroud)


小智 9

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


Urv*_*att 5

将此类添加到您的 css 文件中,它将完美地执行以下步骤:

1)首先创建这个

<div class="center-role-form">
  <!--your div (contrent) place here-->
</div>
Run Code Online (Sandbox Code Playgroud)

2)将其添加到您的CSS中

.center-role-form {
    width: fit-content;
    text-align: center;
    margin: 1em auto;
    display: table;
}
Run Code Online (Sandbox Code Playgroud)


Orr*_*len 5

九年后,我认为是时候推出新版本了。这是我的两个(现在是一个)收藏夹。

余量

设置marginauto。你应该知道的方向顺序margin: *top* *right* *bottom* *left*;margin: *top&bottom* *left&right*

aside{
    display: block;
    width: 50px;
    height: 100px;
    background-color: green;
    float: left;
}

article{
    height: 100px;
    margin: 0 0 0 50px; /* 50px aside width */
    background-color: grey;
}

div{
  margin: 0 auto;
  display:block;
  width: 60px;
  height: 60px;
  background-color: blue;
  color: white;
}
Run Code Online (Sandbox Code Playgroud)
<!DOCTYPE html>
<html>
    <head>
    </head>
    <body>
        <aside>
        </aside>
        <article>           
                <div>The div</div>
        </article>
    </body>
</html>
Run Code Online (Sandbox Code Playgroud)

中心:已描述,请勿使用!

使用<center></center>标签来包装您的标签<div></div>

例:

aside{
    display:block;
    background-color:green;
    width: 50px;
    height: 100px;
    float: left;
}

center{
    display:block;
    background-color:grey;
    height: 100px;
    margin-left: 50px; /* Width of the aside */
}

div{
    display:block; 
    width: 60px; 
    height: 60px; 
    background-color:blue;
    color: white;
}
Run Code Online (Sandbox Code Playgroud)
<!DOCTYPE html>
<html>
    <head>
    </head>
    <body>
        <aside>
        </aside>
        <article>
            <center>
                <div>The div</div>
            </center>
        </article>
    </body>
</html>
Run Code Online (Sandbox Code Playgroud)


P.P*_*kov 5

如果您知道div的宽度并且是固定的,则可以使用以下CSS:

margin-left: calc(50% - 'half-of-your-div-width');
Run Code Online (Sandbox Code Playgroud)

其中“您的div宽度的一半”应该(显然是)div宽度的一半。