How to dynamically center elements inside a div
for a container with elements inside like this:
<div id="container"> <div class="item">Item</div> <div class="item">Item</div> <div class="item">Item</div> <div class="item">Item</div> <div class="item">Item</div> <div class="item">Item</div> <div class="item">Item</div> <div class="item">Item</div> </div> #container { width: 600px; border: 1px solid #CCC; } #container .item { background: red; display:inline-block; width: 50px; height: 50px; } Is there a way with CSS (without JS) to automatically center elements with equal margins. Without using a table?
thanks
+4
2 answers
Adding text-align:center;into the container centers all the elements.
You don't want to use a table, but you can still tell the browser that it will look like a table :-) So, what about this CSS:
#container { width: 600px; border: 1px solid #CCC; display: table; border-spacing:20px 0; /* this is the value that controls the margin */ } #container .item { background: red; display: table-cell; width: 50px; height: 50px; } +4
You can play with fields as follows:
#container { width: 600px; border: 1px solid #CCC; } #container .item { background: red; display:inline-block; width: 50px; height: 50px; margin-left: 1.4%; margin-right: 1.4%; } Play the fiddle: http://jsfiddle.net/zrhLt/9/
+1