1

I have 4 divs, one outer, and 3 inner divs that I want to align in the same row inside the main div. By default the divs are stacked one on top of another inside the main div, so I used float to make them appear in a row.

But once adding float, the divs no longer appear inside the main div. How can I line up the 3 divs inside that main div using CSS?

<div id="main" style="border: solid 1px black;float:left;">
  <div id="left" style="border: solid 1px red;">
    Left
  </div>
  <div id="middle" style="border: solid 1px green;">
    Middle
  </div>
  <div id="right" style="border: solid 1px blue;">
    Right
  </div>
</div>
Youssouf Oumar
  • 29,373
  • 11
  • 46
  • 65
Coding Duchess
  • 6,445
  • 20
  • 113
  • 209

4 Answers4

2

You could simply use Flexbox or CSS Grid, simple and modern way to create layouts, like so:

#main{
  display:grid;
  grid-template-columns: 1fr 1fr 1fr;
}
<div id="main" style="border: solid 1px black;">
    <div id="left" style="border: solid 1px red;">
      Left
    </div>
    <div id="middle" style="border: solid 1px green;">
      Middle
    </div>
    <div id="right" style="border: solid 1px blue;">
      Right
    </div>
</div>
Youssouf Oumar
  • 29,373
  • 11
  • 46
  • 65
2

You just need to add display:flex; in your parent div.

<div id="main" style="border: solid 1px black;float:left;display:flex;">
    <div id="left" style="border: solid 1px red;">
    Left
    </div>
    <div id="middle" style="border: solid 1px green;">
    Middle
    </div>
    <div id="right" style="border: solid 1px blue;">
    Right
    </div>
</div>
Sumit Sharma
  • 1,192
  • 1
  • 4
  • 18
1

DIV standard display is block. You need to change the outer DIV to display: flex. The standard behavior of display flex is to put the child DIVs in a row.

If you want to centralize them in the vertical and horizontal axis, you can use along display: flex, align-items: center and justify-content: center.

Float is used when you want to position an image near a text. Don't use this type of position for this case.

Alex_Lima84
  • 110
  • 10
0

You can use flex with flex: basis: 100%; on each flex-item to have the inner divs span the full width. If you just want them to be next to each other and not span the full width of the row you can use inline-flex.

#main {
  display: flex;
}

#left,
#middle,
#right {
  flex-basis: 100%;
}
<div id="main" style="border: solid 1px black;">
  <div id="left" style="border: solid 1px red;">
    Left
  </div>
  <div id="middle" style="border: solid 1px green;">
    Middle
  </div>
  <div id="right" style="border: solid 1px blue;">
    Right
  </div>
</div>
Kameron
  • 10,240
  • 4
  • 13
  • 26