Jan Van Looveren Jan Van Looveren - 3 months ago 17
HTML Question

How to center multiple divs inside a container in CSS

I am testing to center divider like the style of windows metro.
if you check following HTML code:

.container {
height: 300px;
width: 70%;
background: #EEE;
margin: 10px auto;
position: relative;
}
.block {
background: green;
height: 100px;
width: 100px;
float: left;
margin: 10px;
}


The CSS:

<div class="container">
<div class="block">1. name of the company</div>
<div class="block">2. name of the company</div>
<div class="block">3. name of the company</div>
<div class="block">4. name of the company</div>
<div class="block">5. name of the company</div>
<div class="block">6. name of the company</div>
<div class="block">7. name of the company</div>
<div class="block">8. name of the company</div>
</div>


http://jsfiddle.net/jansor/Np4tA/

The grey box is 70% and centering on the screen that is correct, but when I make the window wider and the green dividers are moving, you can see that the green boxes at some point are not centered.

I am searching for this already the whole day :s

How can help me on this one?

Answer

You could apply the style text-align:center; to your container and display your .blocks as inline-block elements:

.container {
  width: 70%;
  background: #eee;
  margin: 10px auto;
  position: relative;
  text-align:center;
}

.block {
  background: green;
  height: 100px;
  width: 100px;
  display:inline-block;
  margin: 10px;
}
<div class="container">
   
        <div class="block">1. name of the company</div><!--
     --><div class="block">2. name of the company</div><!--
     --><div class="block">3. name of the company</div><!--
     --><div class="block">4. name of the company</div><!--
     --><div class="block">5. name of the company</div><!--
     --><div class="block">6. name of the company</div><!--
     --><div class="block">7. name of the company</div><!--
     --><div class="block">8. name of the company</div>
</div>

Here's an updated Fiddle

Notice I've commented out the white-space between your <div>s. Because the elements are now displayed inline, your spaces will be acknowledged. This is one of many ways to 'fight the space'.