CSS Fudamentals: Containing Children

CSS Fundamentals: Containing Children

I’ve received multiple requests for simpler CSS tutorials that teach the tricky fundamentals. This will serve as the first entry in a series that will receive new additions sporadically each month. Today, we’ll be reviewing the overflow: hidden, and clearfix tricks to force a parent div to contains its children.

The Overflow: Hidden Trick

Have you ever noticed that when you float all of the children elements within a div, the parent takes up zero space? For example, in your code editor, adding the following within the body tag.

<div id="container">
  <div id="main">

  </div>
  <div id="sidebar">

  </div>
</div>

Now, let’s add a bit of CSS to simulate a typical website.

#container {
	background: red;
	width: 800px;
	padding-bottom: 2em; }

#main {
	background: green;
	height: 500px;
	width: 600px;
	float: right; }

#sidebar {
	background: blue;
	height: 500px;
	width: 200px;
	float: left; }

Above, we’re simply setting background colors and floating the sidebar and main divs to the left and right, respectively. Note the “padding-bottom: 2em;”. This should allow us to see the red background at the very bottom, right? View the page in your browser, and you’ll see:

No Overflow Applied

Where did the red background go? Why isn’t it displaying?

The Solution

When you float all of the children, the parent essentially takes up no space. To better illustrate this fact, let’s set an arbitrary height of 50px to the container, and then reduce the opacity of the children divs so that we can see the red background beneath.

#container {
  .. other styles
  height: 50px; }

#main, #sidebar {
  opacity: .5; }

Refresh your browser, and you’ll see:

Not Contained

How odd. We’ve specified a height of 50px for our container div, yet the main and sidebar divs blatantly overflow its boundaries, like spoiled bratty divs.

Return to your stylesheet, and apply one style:

#container {
  ...other styles
  overflow: hidden;
}

After another refresh, we see:

Not Contained

Well that partially helps. Now, we don’t have to worry about the pubescent children disobeying their parent. Having said that, this really doesn’t help our situation.

“Try to avoid specifying heights as much as possible. There’s usually a smarter method.

The solution is to rip out the height property from our container. Remove the following property.

#container {
  ...other styles
  height: 50px; /* Remove this */
}

One last refresh, and our problem seems to be fixed.

Overflow Applied

You can also remove the opacity properties. They were just for demonstration purposes.

The Rub

The method demonstrated above will work in most cases. However, let’s introduce another variable. What if we want to position an image on the border of our container, so that it overlaps. You’ve seen this effect many times. For the sake of the example, we’ll just use an image of a circle with a transparent background. On a real site, this might represent a “Buy Now” or “Sign Up” button — something cheesy like that.

Circle

Positioning the Circle

Using CSS, let’s position the image in the top right portion of our “website”, overlapping the edges. This is what we want:

Breaking Boundaries

First, we reference the image within our HTML.

<div id="container">
  <img src="circle.png" alt="Buy Now" />
  ...rest of html

Next, return to your stylesheet, and add the following styles.

img {
	position: absolute; 
	right: -100px;
	top: 20px; }

Positioning Context

One might think that this will place the image just over the right edge of the container div. However, he’d be wrong.

Because we have not set a positioning context, the window will be used instead.

No positioning context set

Obviously, this is not what we want. To apply a positioning context to our container div, simply add “position: relative;” to #container. Once we’ve done so, the image will no longer use the window as a reference.

Lost Half

What’s the Problem Now?

But now, we have a new problem! Because we set overflow:hidden to our container div, we’ve somewhat shot ourselves in the foot. How do we break boundaries and take names if overflow is set to hidden? Should we simply accept that this particular website won’t be taking names today? Absolutely not. In these cases, it’s worth using a different method.

The Clearfix Trick

With this method, we’ll use CSS to add content after our container div. This created content will then clear our div, thus forcing it to contain its children. Now obviously we don’t want to see this content, so we need to be sure to hide it from the viewer.

Return to your stylesheet, remove “overflow: hidden;” from your container div, and add the following:

#container {
	... other styles
	_height: 1%; }

#container:after {
	content: ".";
	visibility: hidden;
	display: block;
	clear: both;
	height: 0;
    font-size: 0; }

This might appear complicated, but I assure you that it’s quite simple.

  • _height: Triggers “haslayout” in Internet Explorer, by using the underscore trick to target IE6 directly.
  • content: After the container div, append a period.
  • visibility: We don’t want to see the period, so hide it from the page. (Equal to setting opacity: 0;)
  • display: Forces the period to display as a block-level, rather than inline.
  • clear: The important property. This clears the main and sidebar divs. This is the same as adding an unsemantic <div style=”clear: both;”> to our page.
  • height: Don’t take up any space.
  • font-size: Just a precaution for Firefox. This browser sometimes adds a bit of space after our parent element. Setting the font-size to zero fixes this.
Perfect

Conclusion

Though the overflow:hidden trick is preferable, it’s not always ideal. You need to use the best solution for the task at hand. The important thing is to learn each method, so that you have the tools to solve the puzzle.


Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • http://twitter.com/dwpers Daniel

    Interesting article, thanks for clarifying parent/children relationships.

  • http://davidcarreira.com D. Carreira

    Another well explained tutorial…

    Thanks nettuts!

  • http://twitter.com/bugsyrocker Bugsy

    Fantastic stuff.

    The positioning of the circle answers a question I’ve been wrestling with for a while on one of my current projects. Once I get back to work on Monday I should be able to figure it out now!

    Thanks.

  • http://www.danwellman.co.uk Dan Wellman

    great tutorial Jeff!

    Is clear-fix really a proper hack? It validates I think. I use it all the time, it works really well :)

    • http://www.jeff-way.com Jeffrey Way
      Author

      That’s so funny that you mentioned that. I literally just changed the word “hack” to “trick.” :)

      • Vikrant

        good “way” to define hack & trick

  • http://vasili.duove.com/ Vasili

    I never use the overflow: hidden; trick because I sometimes position things outside of the container and I don’t want to go back and change the CSS. I usually just end up adding a <br class=”clear” /> to the container div; it doesn’t bother me.

    I’ll look forward to the rest of the series! :)

    • http://www.jeff-way.com Jeffrey Way
      Author

      Semantics.

  • S. Sea

    “Fudamentals”?! :)

    -Sean

  • http://myfacefriends.com Myfacefriends

    another amazing tuts! from Jeffrey Way! thanks keep on shinning!

  • http://www.james-harding.com James Harding

    Great tut…

    Is this all still the same with CSS3?

  • Meshach

    Nice, very nice. Nettuts+ is back on track.. :)

    • http://www.jeff-way.com Jeffrey Way
      Author

      Was never off track. :)

    • http://www.quizzpot.com crysfel

      hehehehehehe good joke :D

  • http://codingpad.maryspad.com mary

    Excellent, thanks!! I look forward to the other parts of this series. :)

  • http://www.alfystudio.com Ahmad Alfy

    I’ve used overflow:hidden alot, thanks for the second part. I’ve never used that!
    Please note there’s a typo in the css :
    rightright: -100px;
    Thanks Jeff!

    • http://www.jeff-way.com Jeffrey Way
      Author

      Yeah – that’s a stupid bug with the syntax highlighter plugin. I can’t fix that.

      • http://www.alfystudio.com Ahmad Alfy

        Aha!
        well you’re forgiven :D

      • Jonathan Sells

        Phew, I was going to comment on that as well but thought it was a property or shortcut i wasn’t familiar with.

        So to be clear, it’s a general flaw with the plugin and is only supposed to be”right”, because its all over other tuts as well.

  • Nate

    “Now, we don’t have to worry about the pubescent children disobeying their parent.”

    LOL

  • http://www.rtest.ws Richard Testani

    Curious – why woudn’t floating the #container so it takes up the content fix all of this in the first place?

    Also, what does putting a period at the end of your container do and mean?

    Lastly, does IE6 support :after pseudo selector?

    • http://www.jeff-way.com Jeffrey Way
      Author

      Yes – floating the parent will essentially shrink-wrap the contents. However, this isn’t always possible.

      • http://www.chrisdpratt.com Chris Pratt

        Why is it not always possible? I exclusively solved these problems by floating the container until I learned of overflow:hidden. Since then, I’ve begun to incorporate that method more often except in areas where content must actually overflow.

        However, I’ve never ran into a situation where floating the container was not possible. Clearfix has always just seemed to me a horribly complex and redundant exercise.

      • http://twitter.com/dansicle DN

        Sometimes it’s not possible in the context of the page–meaning you can’t have a float here, or can’t without essentially having to then float all parent elements, which can get increasingly complex. Floating means things can break out of non-floated containers, thus the Floating (Nearly) Everything method is pretty much mandated if you want to control floats by floats.

        I don’t have examples in my head at the moment, but I have that vague, distantly annoyed feeling when I think about floats and positioning together, so maybe there’s something that way too, for large layout-level chunks of the design.

    • Xgen

      Right! I always use floating…

  • http://themeforest.net/user/ponjoh?ref=ponjoh Pontus Johansson

    I’ve always used an empty div with clear:both to clear the floats. I know it’s not semantic at all (which I always strive for) but I haven’t been aware of any other way of doing it. Using :after for this is really smart, so thank you for that. But is there another way of making it work IE6 without the use of the underscore hack or any other hack? I mean, hacks should be avoided because they may cause problems in future browsers.

    • http://www.jeff-way.com Jeffrey Way
      Author

      Not if you place the hack in an external stylesheet that is only imported if the user is browsing with IE6.

      • http://themeforest.net/user/ponjoh?ref=ponjoh Pontus Johansson

        That’s true.
        But hold on, is :before and :after even supported by IE7 and lower? Good ol’ quirksmode.org says it isn’t. Am I missing something here?

      • http://twitter.com/dansicle DN

        That’s what _height is for.

    • Mike J

      zoom: 1; should also trigger the hasLayout property.

  • http://www.quizzpot.com crysfel

    Fundamentals are very important ;) this tutorial is awesome, I wish I could have read this four years ago…

  • Jonas

    The title of the article is currently CSS “Fudamentals” by the way. Maybe that’s intentional. CSS sometimes fills me with FUD.

  • Jason A.

    Excellent article! Still waiting for part 2 of that Login System, though!! =)

    • http://www.jeff-way.com Jeffrey Way
      Author

      Will make a better one soon.

  • Man Mohan Singh

    Nice Tutorial for beginers…great keep it up…

  • http://www.imblog.info Muhammad Adnan

    good tut jeff for beginners !

  • kevinsturf

    very useful stuff here Jeff. thanks for pointing out these stuff.

  • http://webmuch.com Aayush

    Nice Article…love the overflow hidden trick…I use it all the time…

  • http://www.zitrox.com Michael

    #container:after
    after won’t work in IE6, so it’s sometimes better to use the clear:both on the next div or simple include an and create a clr-both class in your css file

  • http://www.zitrox.com Michael

    ouh.. it cleared my b r tag..

    just use a specified clear class on a br tag, can also help

  • Raymi

    Another awesome article as always i have a question tho:

    the whole clearfix trick is a feature only for CSS3? or is it always been there and i’m as a distracted person i never notice this trick? haha :P

    please don’t think i’m a dork :$

    • http://www.jeff-way.com Jeffrey Way
      Author

      Yeah – the clearfix method has been around for a few years.

      • Raymi

        danm!! that would’ve saved me a lot of headaches….well i guess that’s how we learn right? :S

  • Nikki

    Setting overflow: auto on #container would clear the float.

    See: http://www.sitepoint.com/blogs/2005/02/26/simple-clearing-of-floats/

    • http://jarrydcrawford.com/ Jarryd

      But as they explain, it can cause scrollbars to appear. I tried out the overflow: auto; method a couple of times with no success in removing those scrollbars so the hidden option has been suitable for me :)

  • Karl Oakes

    Thanks Jeff. always good to read a clearly explained tut.

  • PablO

    Nice article.
    I have two suggestions:
    1/ use content:”"; (empty string), it will also generate pseudo-element and you won’t have to hide it
    2/ use width:100% instead of ugly (IMO) _height hack. It will also trigger hasLayout in IE and won’t break anything in real browsers ;]

    • http://webdevelopersstudio.com Terri

      Not happy with the hack either, but width:100% makes the container equal the width of the browser window. Not what we want here. Any other suggestions (besides a separate stylesheet)?

  • warzazi

    Good job Jeff, that was awesome !
    actually i have a question, it’s about centering a div with a position:absolute; ?? how can we do that ??

    • Mirek

      Example: div {position: absolute; width: 300px; height: 200px;}

      If you want to center that absolute-positioned div, you can add this:

      top: 50%;
      left: 50%;
      margin: – 100px 0 0 -150px; // top-margin = height/2, left-margin = width/2

      However, when the window is smaller than your div, it will get cropped top left

  • http://itsnotthatfunny.com Michael

    round and round we go, dizzying circles to and fro
    when finally comes like this dissertion
    and fine’ly clears up old confusion.

    like a lightbulb switched from off to on
    i’ll again bow to o b wan

    thanks jeff

  • IQ

    What about using “overflow: auto;” instead of “overflow: hidden;”?
    With ‘auto’, your circle would be shown and the container would still be displayed correctly, no need for clearfix trick

  • Paulo

    Good Ideia Jeff. It Was…
    Thanks For Posting It

  • http://threadbarecanvas.com James Hogan

    Thanks,

    I wasn’t aware of the

    :after selector;
    or the content: property;

    CSS3? This is cool :)

    • http://blog.popstalin.com Jen

      Actually the :after selector is part of CSS2. It’s just, in my experience, not often used because IE doesn’t support it.

      Simple explanation of parents and children, Jeff! Thanks.

  • http://www.mariomelchor.com Mario

    I will try tihs next time. I’ve seen :after being used but never know how to use it.

  • http://www.postjockey.com Kenneth Stein

    Appreciate the time taken to set out this tutorial, and it has me wondering how much effort, time and expense has been wasted because of poorly conceived and executed standardization?
    Obviously there are easier and more robust ways to layout pages, but those ways are sacrificed to appease various companies that have developed inferior technology, BUT possess other resources (money, experts, money, political clout).
    Result: web designers that are skilled at the tricks required to get something simple done. Significant change hindered because time, energy, thought going into how to get a DIV to display correctly rather than imagining how can this technology make genuine difference for people?
    Complete waste of time and while I know it’s FUN to solve puzzles, it’s better if the puzzles weren’t placed there by these companies to waste our time just because they aren’t hitting stride in developing their products.
    Finally, it’s hilarious that you can’t fix the “rightright” bug. The technology we are using is crap. We ought to be so much farther ahead than this it’s really pathetic. Rightright? Rightright?

  • http://www.philohermans.nl Philo

    Nice Article Jeffrey! :)

  • http://www.twitter.com/arnold_c arnold

    will read this later…I havent read any stuff about CSS3..but hey thanks..this is really helpful.

    I need more CSS topics! :)

    thanks J.W

  • Fernando Martinez

    Hi there, this is my first CSS step-by-step tutorial I’ve follow.
    I have one doubt…
    why not use “float:left;” on the parent (#container) instead of all that CSS3 selectors?
    I used float:left; since the beginning of the tutorial and got those childs obey :)

    thanks,
    Fernando

    • Name

      You must use float: left on the parent (#container)! This trick is not necessary!

      • http://www.jeff-way.com Jeffrey Way
        Author

        It’s not always ideal. No need for exclamation points.

  • Eman

    this should be put in a class:

    .hasFloats { _height: 1%; }
    .hasFloats:after {
    content: “.”;
    visibility: hidden;
    display: block;
    clear: both;
    height: 0;
    font-size: 0; }

    then, just add

    class=”hasFloats ..”

    to your parent containers.

  • http://www.Quevin.com Quevin

    So glad everyone is eating up the basics of CSS! Run, my children! Or, #Run:after…

  • j2eehunter

    Really Good article..
    i was searching for these kind of article from many websites.
    Thanks

  • Alex Persegona

    Great tutorial Jeff.

    While I ran across other tutorials that dealt with this very same issue, your’s is very clearly stated (you’re a good teacher).

    Another good example of CSS layout solutions can be found here:

    http://warpspire.com/tipsresources/web-production/css-column-tricks/

    Blessings

  • http://www.vision18.in Saifudeen M
  • http://dorianlyder.blogspot.com/ Dorian Lyder

    I’m loving the clearfix approach. I use overflow a lot and I always get tied up with overflow clipping the children when I want them visible.
    Thanx.

  • Jonster

    Nothing that interesting.
    Positioning relatively the parent div and the absolutely positioned div counts it’s distance form the parent. Basic thing….

    What comes to that :after pseudo-selector, why do you use this anyway?
    CSS without hacks is always better what comes to that _height thing.
    What if you just remove the :after selector and do this:
    place a after the sidebar and remove the padding-bottom from the container?

    • http://www.jeff-way.com Jeffrey Way
      Author

      It’s not really a hack folks. It just saves time. Either use another property that triggers haslayout (like zoom: 1), or place the height declaration within an IE stylesheet and remove the underscore. You’re focusing on the wrong things here.

  • Jonster

    What if you just remove the :after selector and do this:
    place a “” after the sidebar and remove the padding-bottom from the container?

  • Jonster

    What if you just remove the :after selector and do this:
    place a div with styles clear:both and height: 2em after the sidebar and remove the padding-bottom from the container?

    • http://www.jeff-way.com Jeffrey Way
      Author

      Sure you could do that – but it’s unsemantic.

  • http://rcez.info The Short Master

    Great Tutorial man, good tricks, like that. Hoping to see some more very soon.

  • rohithpaul

    nice one !

  • Christian

    Sorry, but I don’t see this working in any browser – IE, Firefox, Opera or Safari. What’s wrong?

  • Christian

    Oh well, I forgot to add ‘position:relative;’ to the container div.