Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

side by side divs

Tags:

html

css

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?

like image 200
Jeremy Avatar asked Jan 19 '10 18:01

Jeremy


People also ask

How do I show two divs side by side?

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.

How do I put two divisions side by side in HTML?

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.

How do I display elements side by side in HTML?

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.


2 Answers

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.

like image 130
zombat Avatar answered Oct 03 '22 01:10

zombat


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.

like image 26
davethegr8 Avatar answered Oct 03 '22 01:10

davethegr8