How to automatically center a div element that is inside another div element
Let's suppose the following开发者_Go百科 use case: for a working example plese look at this link
The HTML code:
<div class="container">
<div class="centerElem">
the width of this div could be variable
</div>
</div>
The css style:
.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*/
}
Right now it works like this:
||the width of this div could be variable| |
And I would like to make working like this, without knowing the width of inner div element:
| |the width of this div could be variable| |
It's a bit annoying because the code in your question doesn't match the code in your jsFiddle,.
Use display: inline-block
on .subcon
, combined with text-align: center
on .container
, which you already have.
Like so: http://jsfiddle.net/thirtydot/euYTQ/66/
Or with the code in your question: http://jsfiddle.net/thirtydot/euYTQ/67/
Adding text-align:center
to the outer div seems to work just fine
Jsfiddle: http://jsfiddle.net/HtfZ4/
精彩评论