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

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

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


当前回答

有很多方法可以让元素居中,可以使用显示属性,位置,浮动,边距。但通常我更喜欢使用flexbox,因为它简单易用。我知道不同的人有不同的偏好,但这完全取决于开发人员的偏好和元素之间的关系。

.parent { 显示:块; } .sub-parent-1 { 显示:flex; justify-content:中心;/ /水平居中 对齐项目:中心;/ /垂直定心 } 身体< > < div class = "父" > < div class = " sub-parent-1”> < div class = " child-1 " >…< / div > < / div > < div class = " child-2 " >…< / div > < div class = " child-3 " >…< / div > < div class = " child-4 " >…< / div > < div class = " child-5 " >…< / div > < / div > 身体< / >

其他回答

有很多方法可以让元素居中,可以使用显示属性,位置,浮动,边距。但通常我更喜欢使用flexbox,因为它简单易用。我知道不同的人有不同的偏好,但这完全取决于开发人员的偏好和元素之间的关系。

.parent { 显示:块; } .sub-parent-1 { 显示:flex; justify-content:中心;/ /水平居中 对齐项目:中心;/ /垂直定心 } 身体< > < div class = "父" > < div class = " sub-parent-1”> < div class = " child-1 " >…< / div > < / div > < div class = " child-2 " >…< / div > < div class = " child-3 " >…< / div > < div class = " child-4 " >…< / div > < div class = " child-5 " >…< / div > < / div > 身体< / >

如果你想使用CSS3:

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

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

我相信现代的方法是在父容器中放置位置-项目:居中

一个例子可以在这里找到:https://1linelayouts.glitch.me

弯曲后,它显示文章

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

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

text-align:中心;在父div应该做的把戏