Search code examples
htmlcssinlinechildren

How to properly align side-by-side blocks in a container


I have a div with display block and in it I have others in inline-block. This is what I have.

display:inline-block case

When I put div inside the first in display: block, with float left, I have this:

display:block with floating case

#container {
    display: block;
    width: 50%; /*Of its parent*/
}

#container > div {
    display: block;
    width: 22%;
    padding: 5px 1.2%;
    float: left;
 }

 /* or

 #container > div {
     display: inline-block;
     width: 22%;
     padding: 5px 1.2%;
 }

 or

 #container > div {
     display: inline-block;
     width: 22%;
     padding: 5px 1.2%;
     float: left;
 }

 */

Please, can someone tells me what it is wrong and help to fix it? Thanks


Solution

  • 5px 1.2% and 22% won't work really well, try

    #container > div {
        display: block;
        width: 25%;
        padding: 5px 1%;
        margin: 0;
        float: left;
     }
    

    #container>div {
      display: block;
      width: 23%;
      padding: 5px 1%;
      margin: 0;
      float: left;
      height: 100px;
    }
    
    .red{
      background: red;
    }
    .green{
      background: green;
    }
    <div id="container">
      <div class="red"></div>
      <div class="green"></div>
      <div class="red"></div>
      <div class="green"></div>
    </div>