I've got 4 divs inside a parent div. To get them to appear side by side, I've given all 4 divs a style with float:left. The divs do appear side by side, but the parent div's height does not grow to encompass the height of the child divs. What am I missing?
To position the divs side by side, we are using the float property to float each . float-child element to the left. Since they are both floating to the left, they will display side by side if there's enough space for both to fit.
We can place content inside the <div> tag. Using CSS property, we can place two <div> tags side by side in HTML. By styling we can place the two division classes side by side.
The first way you can use is the display: inline-block method. This method is a simple and classic CSS technique for positioning elements side by side.
This is a quirk cause by the implementation of floating elements, and occurs when you have a parent element that contains nothing but floating child elements. There are two methods to solve it. One is to set the parent element's overflow
property to hidden
, sometimes known as the overflow method. The other is known as the clearfix method, and involves the use of the :after
pseudo-class.
The clearfix method has the advantage of allowing for specifically positioned elements to "hang" outside of the parent container if you ever need them to, at the expense of a bit of extra CSS and markup. This is the method I prefer, as I utilize hanging elements frequently.
Set overflow: hidden;
on the parent div.
Explanation: floating elements removes them from the regular document flow. So, if a given element contains only floated elements, it will not have any height (or, by extension, width -- unless it has an implicit width that is default on block elements).
Setting the overflow property to hidden tells the parent element to respect the width of it's children, but hide everything that falls outside it's width and height.
Of course, the other option is to add an element after the floated divs, inside the parent, with clear: both;
This makes the last element be positioned after all the floats, within the regular document flow. Since it's inside the parent, the parent's height is whatever the heights of the floated items are, plus regular padding and the height of the cleared item.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With