Align multiple Divs horizontally within a container

Asked

Viewed 51,746 times

5

I have several div with float: left inside another div, which is their container, 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 shown below), but I’m not getting it.

Resultado esperado

Well, I can’t make it work. Follow my CSS and then the result I’m getting.

#container {
    width: 100%;
    border-color: blue;
    text-align: center;
}

.box {
    float: left;
    width: 100px; height: 200px;
    margin: 10px 20px;
}

#box-1 { background-color: red; }
#box-2 { background-color: green; }
#box-3 { background-color: pink; }

As DIVs ficam alinhadas à esquerda

Divs aren’t getting aligned like I assumed it would when using text-align: center in the container. How to achieve the expected result?

Jsfiddle

1 answer

4


To get the desired result, I needed to understand what elements with float escape the page rendering flow and become independent elements (within limitations of position, margin, padding, etc.).

To solve the problem, we just had to replace the attribute float: left for display: inline-block in class .box:

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

Thus, each of the DIV becomes an element in the page’s text stream (while maintaining its block behavior, which allows for setting width and height, for example). Thus we obtain the desired result and our DIVs are aligned centrally with the container:

inserir a descrição da imagem aqui

Jsfiddle


The insight of this question came from a problem faced on a website I’m creating for a customer. As always, I’m sharing my knowledge (after verifying that such a question no longer existed) in order to assist my dear SOPT user partners.

  • 2

    Tip: To add IE support that doesn’t interpret display: inline-block -> Also add *display: inline; *zoom: 1;

  • I’m totally disregarding IE :-)

  • 1

    Thanks Tiago, you helped me solve a problem that was getting on my nerves, Thanks..........

Browser other questions tagged

You are not signed in. Login or sign up in order to post.