要居中一个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应该做的把戏

如果你想使用CSS3:

position:absolute;
left:calc(50% - PutTheSizeOfTheHalfOfYourElementpx);

您可能需要做进一步的搜索,以弄清楚如何使百分比适合元素的宽度。

只以特定的子为中心:

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

设置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>

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