I want two divs close to each other in the same row.
HTML:
<div id="container">
<div id="block1"></div>
<div id="block2"></div>
</div>
CSS:
#block1 {
width: 40%;
height: 50px;
background-color: blue;
display: inline-block;
}
#block2 {
width: 40%;
height: 50px;
background-color: yellow;
display: inline-block;
}
So far so good…
But when I add some text or something else like a p or whatever in one of the divs, this happens
<div id="container">
<div id="block1">asdadssa</div>
<div id="block2"></div>
</div>
Why is this happening and what should I do to properly achieve my desire?
Try float:left
your block1 and block2
Ok that works I know but… by giving them a float, the container parent will “lose” them.
(The white background in the image is the container)
Yes it will lose them, so you should float
the parent too and give it a full width
, this is why the flexbox are used, if you want you can try that
1 Like
Ok but I specifically made the container. I want all my elements to be in a white centered box.
If you want all the elements in the container, you should float it, thats how the elements are arranged from left to right, that’s the reason flexbox is used, you need not worry the children going out of parent container, it’s your choice though
1 Like
Thank you for the tip! I’ll look into flexbox.
Meanwhile… can you explain why is that happening? I mean… it doesn’t make sense for me why that thing is hapenning.
To be simple, Consider a parent element containing only floated elements, it won’t have a shape, that’s the reason the parent element loses the default shape it had. You can understand it better here,
1 Like