如标题所述,我想将父 div 居中,其中父 div 检索其所有子 div 的宽度。
这是我用来检索子 div 宽度的代码:
.parent
{
background-color: yellow;
display: inline-block;
font-size: 0;
/*How could I center this div? I used to do: margin-left: auto; margin-right: auto;
however for this I need to assign a fixed width. I want to assign the width of the
content inside the div.*/
}
.child
{
height: 100px;
width: 100px;
border: 1px solid red;
display: inline-block;
}
来源:http://jsfiddle.net/53me4f8e/
如何让这个 div 居中?
最佳答案
居中对齐父元素的文本,在本例中为 body
。 .parent
显示为 inline-block
,这意味着它的行为类似于内联元素,因此居中:
body{
text-align: center;
}
请注意,因为 text-align
是继承的,您可能希望将文本对齐恢复为 left
(或 right
,具体取决于.parent
的偏好):
.parent{
text-align: left;
/* Other styles.. */
}
关于html - 将父 div 居中,而 width 检索子 div 的宽度值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30667639/