如何自动居中另一个div元素内的div元素

时间:2011-10-07 10:59:48

标签: css

让我们假设以下用例: 一个工作的例子请看这个link

HTML代码:

<div class="container">
    <div class="centerElem">
         the width of this div could be variable
    </div>
</div>

css风格:

.container {
    width: 500px; /*this can also change */
}
.container .centerElem{
    margin-right: auto /*unfortunately, it works only if I set properly the width*/
    margin-left: auto /*unfortunately, it works only if I set properly the width*/
}

现在它的工作原理如下:

        ||the width of this div could be variable|                            |

我想在不知道内部div元素的宽度的情况下做这样的工作:

        |                |the width of this div could be variable|            |

2 个答案:

答案 0 :(得分:4)

这有点烦人,因为你问题中的代码与jsFiddle中的代码不匹配,。

使用display: inline-block上的.subcon,结合text-align: center上已有的.container

像这样:http://jsfiddle.net/thirtydot/euYTQ/66/

或使用您问题中的代码:http://jsfiddle.net/thirtydot/euYTQ/67/

答案 1 :(得分:0)

text-align:center添加到外部div似乎可以正常工作

Jsfiddle:http://jsfiddle.net/HtfZ4/