将父div作为居中,宽度检索子div的宽度值

Bar*_*osy 1 html css

正如标题告诉你的那样,我希望将父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;
}
Run Code Online (Sandbox Code Playgroud)

资料来源:http://jsfiddle.net/53me4f8e/

我怎样才能把这个div放在中心?

Geo*_*rge 6

在这种情况下,集中对齐父元素的文本body..parent显示为a inline-block,表示它的行为类似于内联元素,因此居中:

body{
    text-align: center;
}
Run Code Online (Sandbox Code Playgroud)

注意,因为text-align是继承的,您可能希望将文本对齐恢复为left(或right,取决于首选项).parent:

.parent{
  text-align: left;
  /* Other styles.. */
}
Run Code Online (Sandbox Code Playgroud)

的jsfiddle