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.


Add Comment

Discussion 127 Comments

Comment Page 1 of 21 2
  1. Daniel says:

    Interesting article, thanks for clarifying parent/children relationships.

  2. D. Carreira says:

    Another well explained tutorial…

    Thanks nettuts!

  3. Bugsy says:

    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.

  4. Dan Wellman says:

    great tutorial Jeff!

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

  5. Vasili says:

    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! :)

  6. S. Sea says:

    “Fudamentals”?! :)

    -Sean

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

  8. Great tut…

    Is this all still the same with CSS3?

  9. Meshach says:

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

  10. mary says:

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

  11. Ahmad Alfy says:

    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!

    • Jeffrey Way says:
      Author

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

      • Ahmad Alfy says:

        Aha!
        well you’re forgiven :D

      • Jonathan Sells says:

        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.

  12. Nate says:

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

    LOL

  13. 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?

    • Jeffrey Way says:
      Author

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

      • Chris Pratt says:

        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.

      • DN says:

        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 says:

      Right! I always use floating…

  14. 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.

  15. crysfel says:

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

  16. Jonas says:

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

  17. Jason A. says:

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

  18. Man Mohan Singh says:

    Nice Tutorial for beginers…great keep it up…

  19. good tut jeff for beginners !

  20. kevinsturf says:

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

  21. Aayush says:

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

  22. Michael says:

    #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

  23. Michael says:

    ouh.. it cleared my b r tag..

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

  24. Raymi says:

    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 :$

  25. Nikki says:

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

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

    • Jarryd says:

      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 :)

  26. Karl Oakes says:

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

  27. PablO says:

    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 ;]

    • Terri says:

      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)?

  28. warzazi says:

    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 says:

      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

  29. Michael says:

    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

  30. IQ says:

    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

  31. Paulo says:

    Good Ideia Jeff. It Was…
    Thanks For Posting It

  32. James Hogan says:

    Thanks,

    I wasn’t aware of the

    :after selector;
    or the content: property;

    CSS3? This is cool :)

    • Jen says:

      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.

  33. Mario says:

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

  34. 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?

  35. Philo says:

    Nice Article Jeffrey! :)

  36. arnold says:

    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

  37. Fernando Martinez says:

    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

  38. Eman says:

    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.

  39. Quevin says:

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

  40. j2eehunter says:

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

  41. Alex Persegona says:

    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

  42. Dorian Lyder says:

    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.

  43. Jonster says:

    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?

    • Jeffrey Way says:
      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.

  44. Jonster says:

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

  45. Jonster says:

    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?

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

  47. rohithpaul says:

    nice one !

  48. Christian says:

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

  49. Christian says:

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

Comment Page 1 of 21 2

Add a Comment

To add a code snippet to your comment, please wrap your code like so: <pre name="code" class="html">YOUR CODE</pre>. You can replace the class name with "js," "css," "sql," or "php." If there are any "<" or ">" within your code, please search and replace them with: &lt; and &gt; respectively.