要居中一个HTML元素,我可以使用CSS左:50%;。但是,这使得元素相对于整个窗口居中。

我有一个元素,它是<div>元素的子元素,我想让子元素以<div>这个父元素居中,而不是整个窗口。

我不希望容器<div>的所有内容居中,只是一个特定的子。


当前回答

设置text-align:中心;到父div,页边距:auto;到子div。

#parent { text-align:center; background-color:blue; height:400px; width:600px; } .block { height:100px; width:200px; text-align:left; } .center { margin:auto; background-color:green; } .left { margin:auto auto auto 0; background-color:red; } .right { margin:auto 0 auto auto; background-color:yellow; } <div id="parent"> <div id="child1" class="block center"> a block to align center and with text aligned left </div> <div id="child2" class="block left"> a block to align left and with text aligned left </div> <div id="child3" class="block right"> a block to align right and with text aligned left </div> </div>

这是一个很好的资源来集中几乎任何东西。 http://howtocenterincss.com/

其他回答

设置text-align:中心;到父div,页边距:auto;到子div。

#parent { text-align:center; background-color:blue; height:400px; width:600px; } .block { height:100px; width:200px; text-align:left; } .center { margin:auto; background-color:green; } .left { margin:auto auto auto 0; background-color:red; } .right { margin:auto 0 auto auto; background-color:yellow; } <div id="parent"> <div id="child1" class="block center"> a block to align center and with text aligned left </div> <div id="child2" class="block left"> a block to align left and with text aligned left </div> <div id="child3" class="block right"> a block to align right and with text aligned left </div> </div>

这是一个很好的资源来集中几乎任何东西。 http://howtocenterincss.com/

你可以像这样使用bootstrap flex类名:

<div class="d-flex justify-content-center">
    // the elements you want to center
</div>

即使里面有很多元素也可以。

CSS

  body{
    text-align:center;
    }
    .divWrapper{
    width:960px //Change it the to width of the parent you want
    margin: 0 auto;
    text-align:left;
    }

HTML

<div class="divWrapper">Tada!!</div>

这应该使div居中

2016年HTML5 + CSS3方法

CSS

div#relative{
  position:relative;
}

div#thisDiv{
  position:absolute;
  left:50%;
  transform: translateX(-50%);
  -webkit-transform: translateX(-50%);
}

HTML

<div id="relative">
  <div id="thisDiv">Bla bla bla</div>
</div>

Fiddledlidle

https://jsfiddle.net/1z7m83dx/

只以特定的子为中心:

.parent { 身高:100 px; 背景颜色:灰色; 位置:相对; } .child { 背景颜色:白色; 位置:绝对的; 上图:0; 底部:0; 左:0; 右:0; 宽度:20 px; 高度:20 px; 保证金:汽车; } < div class = "父" > < span class = "孩子" >你好> < /跨度 < / div >

或者,你也可以使用flex,但是那样会把所有的子节点居中

.parent { 身高:100 px; 背景颜色:灰色; 显示:flex; justify-content:中心; 对齐项目:中心; } .child { 背景颜色:白色; } < div class = "父" > < span class = "孩子" >你好> < /跨度 < / div >

弯曲后,它显示文章

.container { 显示:flex; 颜色:蓝色; 背景颜色:黄色; justify-content:中心; } < div class = "容器" > < div > < / div元素> < / div > 如果你水平和垂直地设置元素中心。

.container { 显示:flex; 颜色:蓝色; 身高:100 px; 背景颜色:黄色; justify-content:中心; 对齐项目:中心; } < div class = "容器" > < div > < / div元素> < / div >