Align horizontally multiple DIVs within a container

5

I have several div with float: left inside another div, which is the container of them, according to code:

<div id="container">
    <div id="box-1" class="box">1</div>
    <div id="box-2" class="box">2</div>
    <div id="box-3" class="box">3</div>
</div>

I'm trying to align them horizontally inside the container (as pictured below), but I'm not getting it.

Well,Icannotmakeitwork.Here'smyCSSandthentheresultI'mgetting.

#container{width:100%;border-color:blue;text-align:center;}.box{float:left;width:100px;height:200px;margin:10px20px;}#box-1{background-color:red;}#box-2{background-color:green;}#box-3{background-color:pink;}

DIVs are not getting aligned like I assumed would happen when using text-align: center in the container. How to achieve the expected result?

JSFiddle

    
asked by anonymous 26.05.2014 / 15:36

1 answer

4

In order to get the desired result, I had to understand that elements with float run out of the rendering flow of the page and become independent elements (within the limitations of position , margin , padding , etc.) / p>

In order to solve the problem, we just needed to replace the float: left attribute with display: inline-block in class .box :

.box {
    display: inline-block;
    /* o resto permanece igual */
}

Thus, each of the DIV becomes an element in the text flow of the page (while maintaining its block behavior, which allows the definition of width and height, for example). We get the desired result and our DIVs are aligned centrally in relation to the container:

JSFiddle

The insight of this question came from a problem I faced with a site I'm designing for a client. As always, I am sharing my knowledge ( after verifying if this question no longer existed ) in order to assist my dear users of SOPT users.     

26.05.2014 / 15:36