PDKnight PDKnight - 19 days ago 7
CSS Question

Centering floated elements with custom width

Today I am facing a big problem with centering floated elements that have set custom width. For better explanation I made a snippet for you:



body { text-align: center; }
.square {
width: 20%; height: 100px;
background: cornflowerblue;
float: left;
}

.container {
display: inline-block;
}

<div>
<div class="container">
<div class="square">a</div>
<div class="square">b</div>
<div class="square">c</div>
</div>
</div>
<br>
<div>
<div class="container">
<div class="square">a</div>
<div class="square">b</div>
<div class="square">c</div>
<div class="square">d</div>
<div class="square">e</div>
</div>
</div>





The problem is that first three squares get shrinked after centering.

The reason why I am floating the elements is that the second container has to be same as first container and it must contain 5 elements (to cover full width of document). Here is how it looks like without floating (see the gabs between elements):



body { text-align: center; }
.square {
width: 20%; height: 100px;
background: cornflowerblue;
display: inline-block;
}

.container {
display: block;
}

<div>
<div class="container">
<div class="square">a</div>
<div class="square">b</div>
<div class="square">c</div>
</div>
</div>
<br>
<div>
<div class="container">
<div class="square">a</div>
<div class="square">b</div>
<div class="square">c</div>
<div class="square">d</div>
<div class="square">e</div>
</div>
</div>





Now the elements have right width, but the second line doesn't cover width of document because of the gabs between elements.

Is there any way to have floated elements with custom width centered? Which styles I should use for container element?

Vel Vel
Answer

OK, I think I got what you need

.square {
width: 20%; height: 100px;
background: cornflowerblue;
display: inline-block;
font-size: 1rem;
}

.container {
display: block;
font-size:0;
}

jsfiddle