I have 4 DIVs, one outer, and 3 inner divs that I want to align in the same row inside the main DIV
<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>
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 tha main div using css?
CodePudding user response:
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>
CodePudding user response:
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>
CodePudding user response:
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.
CodePudding user response:
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>