Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS: Basic layout question - keeping nested elements inside each other

I keep finding that if I have nested divs inside each other, and one of the inner ones is floated, the outer one won't expand around it.

Example:

<div style='background-color:red; '>
    asdfasdf
    <div style='float:left; background-color:blue; width:400px; height:400px;'>
        asdfasdfasdfasdfasdfasdfasdf<br />
        asdfasdfasdfasdfasdfasdfasdf<br />
        asdfasdfasdfasdfasdfasdfasdf<br />
        asdfasdfasdfasdfasdfasdfasdf<br />
        asdfasdfasdfasdfasdfasdfasdf<br />
        asdfasdfasdfasdfasdfasdfasdf<br />
        asdfasdfasdfasdfasdfasdfasdf<br />
        asdfasdfasdfasdfasdfasdfasdf<br />
        asdfasdfasdfasdfasdfasdfasdf<br />
        asdfasdfasdfasdfasdfasdfasdf<br />
        asdfasdfasdfasdfasdfasdfasdf<br />
    </div>
    asdfasdf
</div>

What do I need to do to the outer div to make it cover the inner one? IE: Put it's border/background color all the way around it?

Also, is there a general principle I am bumping up against here? If so, what should I look up to get a solid understanding of what it is?

Thanks!

Edit

Hi All,

Thanks for the answers, semantically correct and no, and for the links.

Though I will end up using overflow in the final work, I will leave Ant P's answer as accepted, as it was the first one that really worked, and got me out of a short term jam, even though it offends semantic sensibilities.

As a long-time html hack trying to move to decent css layouts, I can certainly understand, and sympathize with, using semantically incorrect hack that gets the job done, though I am sure he will change that habit after this =o)

like image 433
Eli Avatar asked Dec 03 '08 02:12

Eli


People also ask

How do you float a div next to each other?

With CSS properties, you can easily put two <div> next to each other in HTML. Use the CSS property float to achieve this. With that, add height:100px and set margin.

How do I access nested elements in CSS?

CSS Selector - How to use CSS nested element Selector The element element is called nest selector or Descendant Selector. It selects elements inside elements. We can use Descendant Selector to select an element based on its status as a descendant of another element.

What are three types of layouts CSS?

CSS layout types: Fixed, Elastic, and Fluid.


2 Answers

You can do it strictly with CSS using overflow:hidden

<div style='background-color:red;overflow:hidden;'>
...
</div>
like image 80
themis Avatar answered Oct 23 '22 10:10

themis


If you are the type that likes explanations (rather than just "do this") here are some excellent articles that explain several methods:

Simple Clearing of Floats

How to Clear Floats Without Structural Markup

Clearing Floats

like image 33
J.C. Yamokoski Avatar answered Oct 23 '22 09:10

J.C. Yamokoski