You are on page 1of 108

1.

Wrap Your Mind Around Positioning Contexts

There are actually five position values: static, fixed, relative, absolute and inherit.

Well largely skip over inherit because its pretty self explanatory (simply inherits the
value of its parent) and isnt really supported well in older versions of IE.
The default position value for any element on the page is static. Any element with
a static positioning context will simply fall where you expect it to in the flow of the
document. This of course entirely depends on the structure of your HTML.
Another value that youve no doubt seen is fixed. This essentially anchors an object to
the background so that wherever you place it, there it will stay. We often see this used
on sidebar navigation elements. After scrolling down a long page of content, its a pain
to go back to the top to navigate elsewhere so applying a fixed position to the navigation
means the user never loses site of the menu. Click the image below to see a live
example of this in action.

So there you have three position values that are fairly straightforward and easy to wrap
your mind around. The final two are of course absolute and relative. Lets focus on
explaining these independently and then take a look at how they can be used together
to achieve unique results.

Absolute Positioning
Absolute positioning allows you to remove an object from the typical flow of the
document and place it at a specific point on the page. To see how this works, lets set
up a simple unordered list of items that well turn into clearly discernible rectangles.

As weve already learned, by default these items will have a static position applied. That
means they follow the standard flow of the document and are positioned according to
the margins that Ive placed on the list. Now lets see what happens if I target one of
these list items and apply a value of absolute to the position property.

As you can see, the fourth list item was completely removed from the normal flow and
placed at the top left corner of the browser window. Note that even if there were other
content occupying this position, this element wouldnt care. When something has
absolute positioning applied, it neither affects nor is affected by other elements in the
normal flow of the page.

The reason for absolute positioning is so we can position this item precisely where we
want it. We do this with the top, bottom, left and right CSS properties. For instance, lets
say we wanted the fourth list item to be placed twenty pixels from the topside of the
browser window and twenty pixels from the left side.

To prove our earlier point about absolutely positioned items not interacting with other
content, lets move the fourth list item right into the territory of the other list items. Watch
how it simply overlaps the existing content instead of pushing it around.

As one final note, notice how the fifth list item occupies the position previously held by
the fourth rather than holding its position as if the fourth were still in place. Since the
fourth item has been removed from the flow, everything else will adjust accordingly.

Relative Positioning
Relative positioning works similarly to absolute positioning in that you can use top,
bottom, left and right to scoot an object to a specific point on the page. The primary
difference is the origin or starting point for the element. As we saw above, with absolute
positioning, the starting point was at the very top left of the browser window. Check out
what happens when we apply relative positioning though:

Nothing happened! Or did it? As it turns out, the object is indeed relatively positioned
now, but its starting point is where it normally lies in the flow of the document, not the
top left of the page. Now if we apply the same 20px adjustments that we used before,
the result is quite different.

This time the item was moved relative to its starting position. This is extremely helpful
for when you want to slightly tweak an objects position rather than completely reset it
altogether. Notice that, just as with absolute positioning, the relatively positioned object
doesnt care about other items in the normal low of the page. However, the original
position occupied by the relatively positioned element hasnt been occupied by the next
list item as it did with absolutely positioned elements, instead the document acts as if
the fourth item still occupies that position.

What position: absolute; really does is position the element relative to its first non-
statically-positioned ancestor(inherit doesnt count either). Since there hasnt been
one of those in previous examples, it was simply reset to the origin of the page.
So how does this translate into useful information? It turns out, we can use absolute
positioning on our piece of tape, but we first need to add a positioning context to its
ancestor, the photo. Now, we dont want to absolutely position that element because we
dont want it to move anywhere. Thus, we apply relative positioning to it.

As you can see, the pseudo element has absolute positioning applied, which means it
will choose a starting point given the location of its first non-static ancestor. Since Ive
applied relative positioning to the photo, that item fits this description. So now our piece
of tape will begin at the origin of the photo (even if the photo moves due to browser
resizing).

Now that we have found the starting position that we were looking for, we can tweak the
top and left values to nudge the tape into place. Notice that Ive applied a negative value
to the top property so the tape sticks out of the image onto the background. The left
position is set to center the tape horizontally (click here to see how the math works out).
01 .photo:before {

02 content: "";
03 height: 20px;

04 width: 100px;

05 background: rgba(255,255,255,0.5);

06 position: absolute;

top: -15px;
07
left: 50px;
08
-webkit-box-shadow: 0px 1px 3px rgba(0,0,0,0.4);
09
-moz-box-shadow: 0px 1px 3px rgba(0,0,0,0.4);
10
box-shadow: 0px 1px 3px rgba(0,0,0,0.4);
11
}

As we can see in the finished version below, combining absolute and relative
positioning was exactly what we needed to pull off the effect that we were going for.

The first is that relative positioning will allow you to tweak an elements position relative
to its normal starting point. The second is that absolute positioning will allow you to
tweak an elements position relative to its first non-statically-positioned ancestor
(defaults to page bounds if none is found). The final piece of information to remember is
that both relatively and absolutely positioned items wont affect the static and fixed items
around them (absolutely positioned items are removed from the flow, relatively
positioned items occupy their original position).
CSS Positioning 101 -A List Apart
If youre a front end developer or a designer who likes to code, CSS-based layouts are at
the very core of your work. In what might be a refresher for some, or even an a-ha! for
others, lets look at the CSS position property to see how we can use it to create
standards-compliant, table-free CSS layouts.
CSS positioning is often misunderstood.
Sometimes, in a bug-fixing fury, we apply
different position values to a given selector until
we get one that works. This is a tedious process
that can work for a time, but it behooves us to
know why specifying something like position:
relative can fix your layout bug. My hope is that
we can learn the position propertys values and
behaviors, and most importantly, how a value can
affect your markup.
The CSS specification offers us
five position properties:static, relative, ab
solute, fixed, and inherit. Each property
serves a specific purpose. Understanding that
purpose is the key to mastering CSS-based layouts.
GET WITH THE FLOW

First, lets take a step back to recognize the world


were working in. Much like our real world, in CSS,
we work within boundaries. In CSS, this boundary
is called thenormal flow. According to the CSS 2.1
spec:
Boxes in the normal flow belong to a formatting context, which may be block or inline, but not
both simultaneously. Block boxes participate in a block formatting context. Inline boxes
participate in an inline formatting context.
Think of a box, as described by the spec as a
wooden blocknot unlike the ones you played
with as a young whippersnapper. Now, think of
the normal flow as a law similar to the law of
gravity. The normal flow of the document is how
your elements stack one on top of each other, from
the top down, in the order in which they appear in
your markup. You may remember stacking
alphabet blocks into giant towers: The normal flow
is no different than those wooden blocks bound by
the law of gravity. As a child, you had one block on
top of another; in your markup, you have one
element after another. What you couldnt do as a
child, however, was give those blocks properties
that could defy the law of gravity. All of the
sudden, CSS seems a lot cooler than those
alphabet blocks.

Static and relativenothing new here

The static and relative position properties


behave like your childhood blocksthey stack as
you would expect. Note that static is the
default position value of an element, should you
fail to apply any other value. If you have three
statically positioned elements in your code, they
will stack one on top of the next, as you might
expect. Lets take a look at an example with three
elements, all with a position value of static:
#box_1 {
position: static;
width: 200px;
height: 200px;
background: #ee3e64;
}

#box_2 {
position: static;
width: 200px;
height: 200px;
background: #44accf;
}

#box_3 {
position: static;
width: 200px;
height: 200px;
background: #b7d84b;
}

In example A, you can see three elements stacked


like a simple tower. Fascinating, isnt it? This is
block building 101. Congratulations!
You can use the static value for simple, single-
column layouts where each element must sit on
top of the next one. If you want to start shifting
those elements around using offset properties such
as top, right, bottom, and left, youre out of
luck. These properties are unavailable to
a static element. In fact, a static element
cant even create a new coordinate system for child
elements. Wait. What? You lost me atcoordinate
system. Roger that, Roger. Lets explain using
the relative value.
Relatively positioned elements behave just like
statically positioned elements; they play well with
others, stack nicely, and dont cause a ruckus.
Hard to believe, right? Take a look at our previous
example. This time, weve applied
the relative value:

#box_1 {
position: relative;
width: 200px;
height: 200px;
background: #ee3e64;
}

#box_2 {
position: relative;
width: 200px;
height: 200px;
background: #44accf;
}

#box_3 {
position: relative;
width: 200px;
height: 200px;
background: #b7d84b;
}

Example B proves that relatively positioned


elements behave exactly the same way as statically
positioned elements. What you may not know is
that elements with arelative position value are
like Clark Kentthey hide far greater powers than
their static siblings.
For starters, we can adjust a relatively positioned
element with offset
properties: top,right, bottom, and left. Using
the markup from our previous example, lets add
an offset position to #box_2:

#box_2 {
position: relative;
left: 200px;
width: 200px;
height: 200px;
background: #44accf;
}

Example C shows this relative positioning in


action. Our three blocks are stacked up nicely, but
this time the blue block (#box_2) is pushed out
200 pixels from the left. This is where we start to
bend the law of gravity to our will. The blue block
is still in the flow of the documentelements are
stacking one on top of the otherbut notice the
green block (#box_3) on the bottom. Its sitting
underneath the blue block, even though the blue
block isnt directly above it. When you use the
offset property to shift a relatively positioned
element, it doesnt affect the element(s) that
follow. The green box is still positioned as if the
blue box were in its non-offset position. Try that
with your alphabet block tower.
Creating a coordinate system for child elements is
another one of the relative positioning propertys
super powers. A coordinate system is a reference
point for offset properties. Recall in example C,
our blue block (#box_2) is not sitting inside of any
other elements, so the coordinate system its using
to offset itself 200 pixels from the left is the
document itself. If we place the #box_2 element
inside of #box_1, well get a different result,
as #box_2 will position itself relative to the
coordinate system from#box_1. For the next
example, we wont change any CSS, well adjust
our HTML to move #box_2 inside of #box_1:

<div id="box_1">
<div id="box_2"></div>
</div>

Example D shows our new markup. Because of the


new coordinate system, the blue block measures
its offset 200 pixels from the left of the red block
(#box_1) instead of the document. This practice is
more common with elements set to position:
absolutethe way you wish you could have built
towers when you were younger.

Absoluteanywhere, anytime
If the relative value acts like Superman, then
the absolute value mirrors Inceptiona place
where you design your own world. Unlike
the static and relative values, an absolutely
positioned element is removed from the normal
flow. This means you can put it anywhere, and it
wont affect or be affected by any other element in
the flow. Think of it as an element with a giant
strip of velcro on its back. Just tell it where to stick
and it sticks. Exactly like the relative value,
absolutely positioned elements respond to offset
properties for positioning. You can set an element
to top: 100px and left: 200px; and that
element will sit exactly 100px from the top and
200px from the left of the document. Lets look at
an example using four elements:

#box_1 {
position: absolute;
top: 0;
left: 0;
width: 200px;
height: 200px;
background: #ee3e64;
}
#box_2 {
position: absolute;
top: 0;
right: 0;
width: 200px;
height: 200px;
background: #44accf;
}
#box_3 {
position: absolute;
bottom: 0;
left: 0;
width: 200px;
height: 200px;
background: #b7d84b;
}
#box_4 {
position: absolute;
bottom: 0;
right: 0;
width: 200px;
height: 200px;
background: #ebde52;
}

Example E shows four boxes, each in a corner of


the browser window. Since we set each
boxs position value to absolute, weve
essentially velcroed a box to each corner of our
browser window. As you resize the browser, those
boxes will stay in their respective corners. If you
shrink the browser window so that the boxes
overlap, youll notice that there is no interaction at
allthats because theyre out of the documents
normal flow.
Just
like relative elements, absolute elements
create a new coordinate system for child
elements. Example F extends Example E, with an
orange element set inside each box. Notice the
offset coordinates are in respect to each parent
element.
Not to be outdone by other position property
values, the absolute value offers some really cool
functionality using the offset property. Use two or
all four offset properties, and you can stretch an
element without defining any width or heightits
bound only by its parent element or the document
itself. Lets see it in action. Consider the following
code:

#box_a {
position: absolute;
top: 10px;
right: 10px;
bottom: 10px;
left: 10px;
background: red;
}
#box_b {
position: absolute;
top: 20px;
right: 20px;
bottom: 20px;
left: 20px;
background: white;
}

In example G weve created a border offset 10


pixels by the document, and its entirely fluid as
the document resizeall
with absolute positioning and offsets. In another
example, we can create a two-column layout that
fills the entire height of the document. Here is the
CSS:

#box_1 {
position: absolute;
top: 0;
right: 20%;
bottom: 0;
left: 0;
background: #ee3e64;
}

#box_2 {
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 80%;
background: #b7d84b;
}

Example H shows a full-screen, two-column


layout. While this likely isnt the best approach to a
two-column layout, it still shows the power
the absolute value holds. Using some creative
thinking you can find several useful applications
for position: absolute. Similar tricks use
only a single offset value. For example:

#box_1 {
width: 200px;
height: 200px;
background: #ee3e64;
}
#box_2 {
position: absolute;
left: 100px;
width: 200px;
height: 200px;
background: #44accf;
}

In example H2, focus on the blue block (#box_2).


Notice how I use only one offset,left: 100px;.
This allows the #box_2 element to maintain its
top edge and still shift 100 pixels to the left. If we
applied a second offset to the top, we would see
that our blue block (#box_2) is pulled to the top of
the document. See that here, in example H3:

#box_2 {
position: absolute;
top: 0;
left: 100px;
width: 200px;
height: 200px;
background: #44accf;
}

Fixedalways there

An element with position: fixed shares all


the rules of an absolutely positioned element,
except that the viewport (browser/device window)
positions the fixedelement, as opposed to any
parent element. Additionally, a fixed element
does not scroll with the document. It stays,
wellfixed. Lets look at an example:

#box_2 {
position: fixed;
bottom: 0;
left: 0;
right: 0;
}

Example I shows a footer with some copyright text


in it as a fixed element. As you scroll, notice that
it doesnt move. Notice that
the left and right offset properties are set to
zero. Since the fixed value behaves similar to
the absolute value, we can stretch the width of
the element to fit the viewport while fixing the
element to the bottom using bottom: 0;. Use
caution with the fixed value: Support in older
browsers is spotty at best. For example, older
versions of Internet Explorer
render fixed elements as static elements. And,
you now know that static elements dont behave
likefixed elements, right? If you do plan to
use fixed elements in a layout, there areseveral
solutions that can help make your element behave
properly in browsers that dont support
the fixed value.
InheritSomething for nothing

As I mentioned at the beginning of this article,


there are five values available to
theposition property. The fifth value
is inherit. It works as the name implies: The
element inherits the value of its parent element.
Typically, position property elements do not
naturally inherit their parents values
the static value is assigned if
no position value is given. Ultimately, you can
type inherit or the parent elements value and
get the same result.
IN ACTION

All this talk and no action. Lets take a look at a


real-world example website that uses all the
position values. Example J shows a typical website
layout with a header, navigation, content, and
footer. Lets walk through each element, discuss
its position property, and why we chose that
property.
Lets start with our #container element. This is
simply the containing element that Im using to
center our content within the viewport.
The #nav element is the first element within
our #container element. No position property
is assigned to the #navelement, so by default, its
set to static. This is fine: We dont need to do
anything to offset this element, or create any new
coordinate systems with it. We will need to do that
with #content on our next element, so for that
element, weve applied a positionproperty
of relative.
Since were not using any offsets here,
the position value has no real influence on
the#content element, but we placed it there to
create a new coordinate system for
the#callout element. Our #callout element is
set to position: absolute, and since its
parent element, #content is set to relative,
the offset properties were using on#callout are
based off the coordinates created by #content.
The #callout element uses a negative 80px pixel
offset on the right to pull the element outside of its
containing parent element. Additionally, Ive used
one of the cooler features of the absolute value
on our #callout element: by setting the top and
bottom offsets to 100px, Ive stretched
the #callout element to the full height of the
document minus the 100px offset on top and
bottom.
Since the #callout element has
an absolute value, it does not affect other
elements. Therefore, we need to add some padding
to the #content element to keep our paragraphs
from disappearing beneath it. Setting the padding
on the right of #contentto 250px keeps our
content in full view for our users. To bring up the
rear, weve added a footer with a fixed position to
keep it fixed to the bottom of the page. As we
scroll, our footer stays in place. Just as we added
padding to the #content to keep our paragraphs
from disappearing under it, we need to do the
same for the #footer element as it is a sibling of
the absolute value. Adding 60px to
the #content elements bottom padding ensures
that we can scroll the entire document and not
miss any text that would normally be hidden under
the #footer element.
Now we have a nice, simple layout with navigation,
some content, a callout area, and a footer
using static,relative, absolute,
and fixed elements. Since were using
the fixed value in this layout, we should
applysome techniques to make sure that older
browsers still respect our design.

Conclusion

With the position propertys power, you can


accomplish many a layout with confidence and
success. Thankfully, 80% of
the position property values have excellent
support in both modern and older browsers.
The fixed value is the one that you should watch
out for. Understanding the core of
these property values gives you a solid CSS-
based layout foundation, limited only by your
imagination. Hopefully, your days of guessing
position values in a last-minute bug fix frenzy are
now over.

Learn CSS Positioning in Ten Steps


This is a fantastically brief overview of the various positioning contexts. Instead of one
long winded article, this page presents a little box with ten tabs. Each tab has a tiny
code snippet and a sentence or two explaining the code. Off to the right is a live
example layout that updates with each tab. This format is fantastic for visually linking
code snippets to the layouts they produce and I highly recommend giving it a look if you
struggle with mostly text explanations like the one above from ALA.

1. position:static
The default positioning for all elements is position:static, which means the
element is not positioned and occurs where it normally would in the
document.
Normally you wouldn't specify this unless you needed to override a
positioning that had been previously set.

#div-1 {
position:static;
}

id = div-before
id = div-1
id = div-1a
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Integer pretium
dui sit amet felis. Integer sit amet diam. Phasellus ultrices viverra velit.
id = div-1b
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Integer pretium
dui sit amet felis. Integer sit amet diam. Phasellus ultrices viverra velit.
Nam mattis, arcu ut bibendum commodo, magna nisi tincidunt tortor, quis
accumsan augue ipsum id lorem.
id = div-1c
id = div-after

2. position:relative
If you specify position:relative, then you can use top or bottom,
and left or rightto move the element relative to where it would normally
occur in the document.
Let's move div-1 down 20 pixels, and to the left 40 pixels:

#div-1 {
position:relative;
top:20px;
left:-40px;
}

Notice the space where div-1 normally would have been if we had not moved
it: now it is an empty space. The next element (div-after) did not move
when we moved div-1. That's because div-1 still occupies that original space
in the document, even though we have moved it.
It appears that position:relative is not very useful, but it will perform an
important task later in this tutorial.
id = div-before
id = div-1
id = div-1a
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Integer pretium
dui sit amet felis. Integer sit amet diam. Phasellus ultrices viverra velit.
id = div-1b
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Integer pretium
dui sit amet felis. Integer sit amet diam. Phasellus ultrices viverra velit.
Nam mattis, arcu ut bibendum commodo, magna nisi tincidunt tortor, quis
accumsan augue ipsum id lorem.
id = div-1c
id = div-after

3. position:absolute
When you specify position:absolute, the element is removed from the
document and placed exactly where you tell it to go.
Let's move div-1a to the top right of the page:

#div-1a {
position:absolute;
top:0;
right:0;
width:200px;
}

Notice that this time, since div-1a was removed from the document, the
other elements on the page were positioned differently: div-1b, div-1c, and
div-after moved up since div-1a was no longer there.
Also notice that div-1a was positioned in the top right corner of the page.
It's nice to be able to position things directly the page, but it's of limited
value.
What I really want is to position div-1a relative to div-1. And that's where
relative position comes back into play.

Footnotes

There is a bug in the Windows IE browser: if you specify a relative width


(like "width:50%") then the width will be based on the parent element
instead of on the positioning element.
id = div-1a
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Integer
pretium dui sit amet felis. Integer sit amet diam. Phasellus ultrices
viverra velit.
id = div-1b
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Integer
pretium dui sit amet felis. Integer sit amet diam. Phasellus ultrices
viverra velit. Nam mattis, arcu ut bibendum commodo, magna nisi
tincidunt tortor, quis accumsan augue ipsum id lorem.
id = div-1c
id = div-after

4. position:relative + position:absolute
If we set relative positioning on div-1, any elements within div-1 will be
positioned relative to div-1. Then if we set absolute positioning on div-1a,
we can move it to the top right of div-1:

#div-1 {
position:relative;
}
#div-1a {
position:absolute;
top:0;
right:0;
width:200px;
}
2. Master Floats
When youre first learning CSS, floats seem like one of the most screwed up layout
systems imaginable. Once you learn to use them on a basic level, you then have to
learn all about how parents containing only floated children have a collapsed height,
which then leads to forty-seven different ways to solve the problem through clearfixes
and overflow manipulations.

Fortunately, in the long run, you do get used to the concepts behind floats and they can
even become so easy to use that you dont give them much thought at all. The only
thing standing between you and that goal is a solid article or two that really digs in and
thoroughly explains float behavior and techniques from the ground up.

Resources To Get You There

Everything You Never Knew About CSS Floats


In this article, I cover nearly the complete gamut of topics regarding floats in CSS. It
starts off with a basic discussion of what floats are and how they work. After this, I talk
about how floats effect the boxes of the elements involved, how floats get weird with
elements of varying heights, the nine rules that cover float behavior and of course the
collapsing height debacle and how to fix it.

What do floats really do anyway? How do they affect the box model of the
elements involved? How do floated elements differ from inline elements? What
are the specific rules governing the position of floated elements? How does the
clear property work and what is it for?

Floats can trip up even experienced developers and understanding their behavior can
really set you free from many of the woes that you face with CSS. Even if you think
you already know all about floats, well dive deep enough that you just might learn
something new!

What Is a Float?

Some elements in CSS are block level elements, which means they automatically start
a new line. For instance, if you create two single word paragraph elements, they wont
flow into each other but will appear on separate lines. Other elements are inline
elements. This means that they appear in line with the previous content. One example
is an anchor tag, which can appear within another element such as a paragraph without
causing any extra whitespace or new lines to occur.

One way to cheat this model of layout is to use floats, which allow a given element to
shift to one side of its line and have other content flow down its side. A right-floated
element will be pushed all the way to the right of its container and have content flow
down its left side and a left-floated element will be pushed all the way to the left side
with content flowing down its right side.

The classic example is when you toss an image in with a paragraph and want the two to
appear side by side rather than stacked. First we create both elements with some
HTML:

Lorem ipsum...
Alone, this code does not produce the effect that we want. The paragraph element is a
block level element that appears on its own line and so the paragraph and the image
are shown stacked in the normal document flow.

We can change this behavior by floating our image to the right. The CSS for this is very
basic:

img {
float: right;
margin: 20px;
}

With this code in place, our image is scooted to the right side of its line and the
paragraph is allowed to flow down its left side. Click here or on the image below to see
and tweak a live example of this code in action.
One interesting thing about the behavior of this image now that it is floated is that our
other content will actually attempt to wrap around it where possible. If we resize our
container or browser window to be narrower, the text simply reflows itself so that it
never touches the image.

How the Box Works

Odds are you already understood this behavior to a decent degree. However, in order to
wield floats properly, you need to understand how these two elements are interacting on
deeper level. For instance, how do we add extra margin between the paragraph and the
image? You might think that this will work:
p {margin: 20px;}
However, this wont put even a single pixel of extra space between the image and the
paragraph. Instead, we have to apply our margin to the image:

img {margin: 20px;}

The question you should be asking yourself is, why? Why wouldnt increasing the
paragraph margin increase the space between the image and the paragraph? The
reason is that were failing to grasp the box model as it pertains to that paragraph.

If youre ever doubtful about how your layout is working on a basic level, try applying a
border or two to see whats going on. If we use this technique on the paragraph, the
result may surprise you.

p {
border: solid 1px black;
}

As you can see, the image is actually inside of the paragraphs box! This solves our
margin riddle. Any margin that we add to the paragraph is being applied way off to the
right of the image, this is why it doesnt increase the space between the image and the
paragraph.

If we wanted the change this behavior so that the paragraph doesnt wrap around the
image, we could float the paragraph to the left and give it a specified width (without
expressing the width, the paragraph is 100% wide and wont fit next to the image).

img {
float: right;
margin: 20px;
}

p {
float: left;
width: 220px;
margin: 20px;
}

Crazy Float Rules

Now we know what a float is and how it affects the boxes of the elements that are
involved. Lets move on to another piece of information that many developers probably
dont understand in the least: the rules that govern a floated elements position.

Its often the case that developers will use floats to govern the positioning of list items,
perhaps in an image gallery or feature listing. Lets see how this works by creating a
simple list full of images.

By default, all the list items will appear in a big vertical stack, which obviously means
that they are block level elements. Even though the images are inline elements, theyll
be governed by their parent block level list items. To fix this, we might float the list items
to the left. When multiple items in a row are floated, they take on a similar effect to a
stream of inline elements. However, as well see, there are some key differences.

li {
float: left;
margin: 4px;
}
Now, if all of our images were the same height, this would be a pretty unremarkable
example. The result would look like a simple image gallery with the images appearing in
order from left to right:
However, our images are not the same height, some of them are 100px tall, others are
150px tall. This causes some seriously wacky results! Click here or on the image below
to see this effect live.

The first time I saw this effect, I was baffled. What in the world was going on here? Why
is image number four off to the right side like that? Shouldnt it be trying to float itself as
far left as possible? If we remove the float and instead use display: inline on the list
items, the result is drastically different.
li {
display: inline;
}
For starters, this example is different in the fact that the images are defaulting to a state
of being vertically aligned along their bottom edges. This causes them to look quite
different than our previous example, but we can fix this with a single line of CSS.

img {
vertical-align: top;
}
Now were starting to look a lot like the float example, only displaying the list items inline
has a much more predictable stacking order. When theres no room on the x-axis for the
next item, it starts back on the left slide in the next line.

So why doesnt our floated image gallery work like this? What strange voodoo governs
floated items?
Translation Required

It turns out, the CSS spec outlines a list of nine rules that govern the behavior of floats.
The problem with this list though is that it was written so that only lawyers and other
boring people can understand it. Heres a direct quote from one of the rules:
If the current box is left-floating, and there are any left-floating boxes generated by
elements earlier in the source document, then for each such earlier box, either the left
outer edge of the current box must be to the right of the right outer edge of the earlier
box, or its top must be lower than the bottom of the earlier box. Analogous rules hold
for right-floating boxes.

Maybe your reading comprehension is higher than mine, but this and the other rules in
the list made my head spin. All this talk of the left outer edge being to the right of the
right outer edge is actually pretty basic stuff dressed up to sound complicated. To make
things simpler, here are Josh Johnsons nine rules for float behavior, translated into
English for your convenience.

1. Floated elements are pushed to the edge of their containers, no further.

2. Any floated element will either appear next to or below a previous floated element.
If the elements are floated left, the second element will appear to the right of the
first. If theyre floated right, the second element will appear to the left of the first.

3. A left-floating box cant be further right than a right-floating box.

4. Floated elements cant go higher than their containers top edge (this gets more
complicated when collapsing margins are involved, see original rule).

5. A floated element cant be higher than a previous block level or floated element.

6. A floated element cant be higher than a previous line of inline elements.

7. One floated element next to another floated element cant stick out past the edge of
its container.

8. A floating box must be placed as high as possible. (No translation necessary)

9. A left-floating box must be put as far to the left as possible, a right-floating box as
far to the right as possible. A higher position is preferred over one that is further to
the left/right. (No translation necessary)
Here we can see that many of these are pretty much common sense, but they must be
explicitly stated so that every person and browser is on the same page. Basically, the
gist of the situation is that floated elements go right up to the specified edge (left or
right), but no further. Unless of course there is another floated element before it, in
which case it just goes next to that one.

The real surprise that confused us before comes in the rules at the end, which state that
floated elements try to stay as high as possible and that this vertical positioning rule
takes precedence over the horizontal left/right floating rule that pushes an item to an
edge.

In our previous example, image number two stretched the height of the line down so
that after image number three, there was still some vertical space for image number
four to squeeze into. Even with these rules in mind, the pattern isnt always easy to
predict.

Just keep in mind that when you have one floated element, the next floated elements
behind it will take up at least the same amount of vertical space or more before
breaking the line and going lower in the flow.
Ads by SenseAd Options
Float Order

One last note regarding the rules that weve laid out here. The second rule has some
interesting implications for the order of items that are floated. Lets say we again have a
list of images numbered one through six, like this:

If we float these images to the left, theyll appear in order, starting at one and going
through six; left to right, top to bottom. However, heres what happens if we float the list
items to the right:

As you can see, the first image actually takes the rightmost position. Similarly, when the
line breaks, the fourth image is placed on the right side. This is why youll rarely see
anyone float a list of navigation elements to the right. To do so screws with the order
and would require undesirable changes in the HTML hierarchy to resolve.

Clearing Floats

Floats are handy for accomplishing some great layout feats like creating columns of
content. However, once declared, they have an effect on the rest of the documents flow
that you might or might not like! For instance, lets say we wanted to throw in a
paragraph after a block of left-floating list items like the one we had above.

The result is probably not going to be what you hoped for:

The answer here is to use the clear property, which makes it so that no floated items
can appear on a given side of the element it is applied to. For instance, lets say we
target the second list item in our little gallery and apply a value of clear: left.
ul li:nth-child(2) {
clear: left;
}
What this code does is tell the browser that the top of the second list item must be
below the bottom of any left-floating items before it (in this case, the first list item). If we
had all floated all of these elements to the right, we wouldve had to use clear:
right instead.
Notice that after this, the rest of the floated items maintain their course. Thats because
theyre still set to float left, the clear property does not somehow cancel this out. This
means that our problem with the paragraph is not fixed by clearing any of the list items.

Instead, what has to happen is that the paragraph element, which is a block level
element that has not been floated, must be cleared. This will make sure it appears
below the floated elements rather than next to them.

p {
clear: both;
}
We technically only needed a left clear here, but when a developer wants to be sure to
clear all floats, its common practice to see the both value used. This change fixed our
problem up nicely!
Float Quirks and Clear Fixes

Theres a peculiar action that takes place when a given element contains only floated
elements: the parent elements height collapses. To illustrate this, lets say we wanted
to put a background color on the unordered list that weve being using in all our
examples. If the elements in the list arent floated, then we need only apply the color to
the background using CSS.

ul {
background: gray;
}

As you can see in the example below, the box that defines the unordered list has been
turned gray and the list items within are stacked on top of each other.
However, the second that we float those list items, that UL contains only floated
elements, and so its height collapses, leaving a newbie developer wondering what the
heck happened to his background color.

There are a number of ways to solve this problem. The easiest and most straightforward
solution is simply to apply an explicit height to the parent element, which is the
unordered list.

ul {
height: 300px;
}

As you can see, this did indeed give us our background fill back. However, this is rarely
the desirable course to take simply because its more convenient in the long run if the
height is automatically computed based on the contents. If we add three more rows of
images to our list now, that height wont be adequate.
Clearfix To The Rescue

This is where the term clear fix, also written clearfix, comes into play. Clearfixes
address this collapsing height problem traditionally through the use of
the clear property.
What developers used to do is create an empty element (often a div) in their HTML on
the same level as the floated items, then apply a class of clearfix to that empty
container. Back in CSS, you would then add clear the floats on the clearfix property.

.clearfix {
clear: both;
}
This immediately fixes the collapsed height issue:

Given what weve already learned, we know exactly why this trick fixed our problem.
The reason the height had collapsed is because the parent contained only floated
children. Now it has one child, albeit an empty one, that isnt floated, so the auto height
works as expected again.

The problem with this method is that no one liked that extra ugly element in the HTML. It
simply wasnt semantic, meaning that it wasnt helping to communicate the clear
hierarchy of the page.

The new fancy fix for this problem is to take advantage of the overflow property, which
governs the functionality of content that extends beyond the boundaries of its containing
box. It turns out that if you set overflow to hidden or auto on the parent item, it fixes the
height collapse!
ul {
overflow: auto;
}
This is definitely the briefest and most elegant solution to fixing the collapsing height
issue and should be your go to strategy. That being said, there will be cases where you
want the overflow of an element to be set to visible, what should you do then?
The answer is to use Nick Gallaghers Micro Clearfix Hack, which uses some genius
CSS to fix this issue. First, it uses :before and :after to add in some content that we can
use to create something in the parent that isnt floated. However, you dont really want
any content in here, so we leave it empty but set the display to table to create an
anonymous cell (empty and takes up no space) and finally use our old friend clear. This
creates the invisible block level item we need to fix the height collapse without extra
HTML markup. Older versions of IE require their own fix so this is thrown in as well.
/* For modern browsers */
.cf:before,
.cf:after {
content:"";
display:table;
}

.cf:after {
clear:both;
}

/* For IE 6/7 (trigger hasLayout) */


.cf {
zoom:1;
}

Conclusion

In this article, we went over a ton of great information, both basic and complicated. We
started with a discussion of how what floats are and how they work on a basic level,
then proceeded to how setting an element to float affects the bordering boxes of the
elements involved so you can properly figure out how to get your margins to work like
you want them to.
Next, we moved onto the basic rules that govern the position of a floated element and
arrived at some interesting conclusions for how floated elements of varying heights will
be positioned as well as how right floated items appear in reverse order.

Finally, we clearly laid out the entire tale of how a parent containing only floated children
will have a collapsed height and how you can solve it based on your particular scenario.

If floats were something that confused you before reading this article, join the club. They
confuse us all at first. Hopefully though you now have an outstanding knowledge of how
floats work and how you can use them to achieve any layout you want.

All About Floats


What is "Float"?
Float is a CSS positioning property. To understand its purpose and origin, we can look
to print design. In a print layout, images may be set into the page such that text wraps
around them as needed. This is commonly and appropriately called "text wrap". Here is
an example of that.

In page layout programs, the boxes that hold the text can be told to honor the text wrap,
or to ignore it. Ignoring the text wrap will allow the words to flow right over the image like
it wasn't even there. This is the difference between that image being part of the flowof
the page (or not). Web design is very similar.
In web design, page elements with the CSS float property applied to them are just
like the images in the print layout where the text flows around them. Floated
elements remain a part of the flow of the web page. This is distinctly different than page
elements that use absolute positioning. Absolutely positioned page elements
are removed from the flow of the webpage, like when the text box in the print layout
was told to ignore the page wrap. Absolutely positioned page elements will not affect
the position of other elements and other elements will not affect them, whether they
touch each other or not.

Setting the float on an element with CSS happens like this:

#sidebar {

float: right;

There are four valid values for the float property. Left and Right float elements those
directions respectively. None (the default) ensures the element will not float
and Inheritwhich will assume the float value from that elements parent element.

What are floats used for?

Aside from the simple example of wrapping text around images, floats can be used to
create entire web layouts.
Floats are also helpful for layout in smaller instances. Take for example this little area of
a web page. If we use float for our little avatar image, when that image changes size
the text in the box will reflow to accommodate:

This same layout could be accomplished using relative positioning on container and
absolute positioning on the avatar as well. In doing it this way, the text would be
unaffected by the avatar and not be able to reflow on a size change.

Clearing the Float

Float's sister property is clear. An element that has the clear property set on it will not
move up adjacent to the float like the float desires, but will move itself down past the
float. Again an illustration probably does more good than words do.
In the above example, the sidebar is floated to the right and is shorter than the main
content area. The footer then is required to jump up into that available space as is
required by the float. To fix this problem, the footer can be cleared to ensure it stays
beneath both floated columns.

#footer {

clear: both;

Clear has four valid values as well. Both is most commonly used, which clears floats
coming from either direction. Left and Right can be used to only clear the float from one
direction respectively. None is the default, which is typically unnecessary unless
removing a clear value from a cascade. Inherit would be the fifth, but is strangly not
supported in Internet Explorer. Clearing only the left or right float, while less commonly
seen in the wild, definitely has its uses.
The Great Collapse

One of the more bewildering things about working with floats is how they can affect the
element that contains them (their "parent" element). If this parent element contained
nothing but floated elements, the height of it would literally collapse to nothing. This isn't
always obvious if the parent doesn't contain any visually noticeable background, but it is
important to be aware of.

As anti-intuitive as collapsing seems to be, the alternative is worse. Consider this


scenario:

If the block element on top were to have automatically expanded to accomodate the
floated element, we would have an unnatural spacing break in the flow of text between
paragraphs, with no practical way of fixing it. If this were the case, us designers would
be complaining much harder about this behavior than we do about collapsing.

Collapsing almost always needs to be dealt with to prevent strange layout and cross-
browser problems. We fix it by clearing the float after the floated elements in the
container but before the close of the container.

Techniques for Clearing Floats

If you are in a situation where you always know what the succeeding element is going to
be, you can apply the clear: both; value to that element and go about your
business. This is ideal as it requires no fancy hacks and no additional elements making
it perfectly semantic. Of course things don't typically work out that way and we need to
have more float-clearing tools in our toolbox.

The Empty Div Method is, quite literally, an empty div. <div style="clear:
both;"></div>. Sometimes you'll see a <br /> element or some other random
element used, but div is the most common because it has no brower default styling,
doesn't have any special function, and is unlikely to be generically styled with CSS.
This method is scorned by semantic purists since its presence has no contexual
meaning at all to the page and is there purely for presentation. Of course in the
strictest sense they are right, but it gets the job done right and doesn't hurt anybody.
The Overflow Method relies on setting the overflow CSS property on a parent
element. If this property is set to auto or hidden on the parent element, the parent will
expand to contain the floats, effectively clearing it for succeeding elements. This
method can be beautifully semantic as it may not require an additional elements.
However if you find yourself adding a new div just to apply this, it is equally as
unsemantic as the empty div method and less adaptable. Also bear in mind that the
overflow property isn't specifically for clearing floats. Be careful not to hide content or
trigger unwanted scrollbars.
The Easy Clearing Method uses a clever CSS pseudo selector (:after) to clear
floats. Rather than setting the overflow on the parent, you apply an additional class
like "clearfix" to it. Then apply this CSS:
.clearfix:after {

content: ".";

visibility: hidden;
display: block;

height: 0;

clear: both;

This will apply a small bit of content, hidden from view, after the parent element
which clears the float. This isn't quite the whole story, as additional code needs to be
used to accomodate for older browsers.
Different scenarios call for different float clearning methods. Take for example a grid of
blocks, each of different types.

To better visually connect the similar blocks, we want to start a new row as we please,
in this case when the color changes. We could use either the overflow or easy clearing
method if each of the color groups had a parent element. Or, we use the empty div
method in between each group. Three wrapping divs that didn't previously exist or three
after divs that didn't previously exist. I'll let you decide which is better.
Problems with Floats

Floats often get beat on for being fragile. The majority of this fragility comes from IE 6
and the slew of float-related bugs it has. As more and more designers are dropping
support for IE 6, you may not care, but for the folks that do care here is a quick
rundown.

Pushdown is a symptom of an element inside a floated item being wider than the
float itself (typically an image). Most browsers will render the image outside the float,
but not have the part sticking out affect other layout. IE will expand the float to
contain the image, often drastically affecting layout. A common example is an image
sticking out of the main content push the sidebar down below.

Quick fix: Make sure you don't have any images that do this, use overflow:
hiddento cut off excess.
Double Margin Bug - Another thing to remember when dealing with IE 6 is that if
you apply a margin in the same direction as the float, it will double the margin. Quick
fix:set display: inline on the float, and don't worry it will remain a block-level
element.
The 3px Jog is when text that is up next to a floated element is mysteriously kicked
away by 3px like a weird forcefield around the float. Quick fix: set a width or height
on the affected text.
In IE 7, the Bottom Margin Bug is when if a floated parent has floated children
inside it, bottom margin on those children is ignored by the parent. Quick fix: using
bottom padding on the parent instead.

Alternatives

If you need text wrapping around images, there really aren't any alternatives for float.
Speaking of which, check out this rather clever technique for wrapping text around
irregular shapes. But for page layout, there definitely are choices. Eric Sol right here on
A List Apart has an article on Faux Absolute Positioning, which is a very interesting
technique that in many ways combines the flexibility of floats with the strength of
absolute positioning. CSS3 has the Template Layout Module that, when widely adopted,
will prove to be the page layout technique of choice.

The Mystery Of The CSS Float Property


While Chris Coyiers pieces are typically brief and to the point, the content on Smashing
Magazine is usually quite expansive with tons of examples and relevant discussion.
This article introduces the concept of floats, tells you all about how to use and clear
them and then launches into a discussion of where you typically see floats being used in
real world sites. If you need to see the theory come alive, this one is for you.

Years ago, when developers first started to make the transition to HTML layouts without
tables, one CSSproperty that suddenly took on a very important role was
thefloat property. The reason that the float property became so common was that, by
default, block-level elements will not line up beside one another in a column-based format.
Since columns are necessary in virtually every CSS layout, this property started to get used
and even overused prolifically.
The CSS float property allows a developer to incorporate table-like columns in an HTML
layout without the use of tables. If it were not for the CSSfloat property, CSS layouts would
not be possible except using absolute and relative positioning which would be messy and
would make the layout unmaintainable.
In this article, well discuss exactly what the float property is and how it affects elements in
particular contexts. Well also take a look at some of the differences that can occur in
connection with this property in the most commonly-used browsers. Finally, well showcase a
few practical uses for the CSS float property. This should provide a well-rounded and
thorough discussion of this property and its impact on CSS development.
Definition and Syntax
The purpose of the CSS float property is, generally speaking, to push a block-level element to
the left or right, taking it out of the flow in relation to other block elements. This allows
naturally-flowing content to wrap around the floated element. This concept is similar to what
you see every day in print literature, where photos and other graphic elements are aligned to
one side while other content (usually text) flows naturally around the left- or right-aligned
element.

Flickr photo by presentday


The photo above shows the Readers sites section of .net magazine, which displays 3 readers
photos each aligned left in their respective columns with text wrapping around the aligned
images. That is the basic idea behind the float property in CSS layouts, and demonstrates one
of the ways it has been used in table-less design.
The effectiveness of using floats in multi-columned layouts was explained by Douglas Bowman
in 2004 in his classic presentation No More Tables:
No More Tables
Bowman explained the principles behind table-less design, using Microsofts old site as a case
study. Floats were used prominently in his mock overhaul of the Microsoft layout.
SYNTAX
The float CSS property can accept one of 4 values: left, right, none, and inherit. It is
declared as shown in the code below.
#sidebar {
float: left;
}
The most commonly-used values are left and right. A value of none is the default, or
initial float value for any element in an HTML page. The value inherit, which can be applied
to nearly any CSS property, does not work in Internet Explorer versions up to and including 7.
The float property does not require the application of any other property on a CSS element
for float to function correctly, however, float will work more effectively under specific
circumstances.
Generally, a floated element should have an explicitly set width (unless it is a replaced
element, like an image). This ensures that the float behaves as expected and helps to avoid
issues in certain browsers.
#sidebar {
float: left;
width: 350px;
}
SPECIFICS ON FLOATED ELEMENTS
Following is a list of exact behaviours of floated elements according to CSS2 Specifications:
A left-floated box will shift to the left until its leftmost margin edge (or border edge if
margins are absent) touches either the edge of the containing block, or the edge of
another floated box
If the size of the floated box exceeds the available horizontal space, the floated box will
be shifted down
Non-positioned, non-floated, block-level elements act as if the floated element is not
there, since the floated element is out of flow in relation to other block elements
Margins of floated boxes do not collapse with margins of adjacent boxes
The root element (<html>) cannot be floated
An inline element that is floated is converted to a block-level element
Float in Practice
One of the most common uses for the float property is to float an image with text wrapping
it. Here is an example:

Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.
Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit
amet quam egestas semper.
Aenean ultricies mi vitae est. Mauris placerat eleifend leo. Quisque sit amet est et sapien
ullamcorper pharetra. Vestibulum erat wisi, condimentum sed, commodo vitae, ornare sit
amet, wisi. Aenean fermentum, elit eget tincidunt condimentum, eros ipsum rutrum orci,
sagittis tempus lacus enim ac dui.
Donec non enim in turpis pulvinar facilisis. Ut felis. Praesent dapibus, neque id cursus faucibus,
tortor neque egestas augue, eu vulputate magna eros eu erat. Aliquam erat volutpat. Nam dui
mi, tincidunt quis, accumsan porttitor, facilisis luctus, metus.
Lifesaver Image from stock.xchng
The CSS applied to the image in the box above is as follows:
img {
float: left;
margin: 0 15px 5px 0;
border: solid 1px #bbb;
}
The only property required to make this effect work is the float property. The other
properties (margin and border) are there for aesthetic reasons. The other elements inside the
box (the <p> tags with text inside them) do not need any styles applied to them.
As mentioned earlier, floated elements are taken out of flow in relation to other block
elements, and so other block elements remain in flow, acting as if the floated element is not
even there. This is demonstrated visually below:

This box is floated left


This <p> element has a different background color to show that it spans the width of its parent,
ignoring the floated element. This inline text, however, wraps around the floated box.
In the above example, the <p> element is a block-level element, so it ignores the floated
element, spanning the width of the container (minus padding). All non-floated, block-level
elements will behave in like manner.
The text in the paragraph is inline, so it flows around the floated element. The floated box is
also given margin settings to offset it from the paragraph, making it visually clear that the
paragraph element is ignoring the floated box.
Clearing Floats
Layout issues with floats are commonly fixed using the CSS clear property, which lets you
clear floated elements from the left or right side, or both sides, of an element.
Lets take a look at an example that commonly occurs a footer wrapping to the right side of a
2-column layout:
Left column floated left
Right column also floated left
Footer
If you view this page in IE6 or IE7, you wont see any problems. The left and right columns are in
place, and the footer is nicely tucked underneath. But in Firefox, Opera, Safari, and Chrome,
youll see the footer jump up beside the left column. This is caused by the float applied to the
columns. This is the correct behaviour, even though it is a more problematic one. To resolve
this issue, we use the aforementioned clearproperty, applied to the footer:
#footer {
clear: both;
}
The result is shown below:
Left column floated left
Right column also floated left
Footer
The clear property will clear only floated elements, so applying clear: both to both
columns would not cause the footer to drop down, because the footer is not a floated element.
So use clear on non-floated elements, and even occasionally on floated elements, to force
page elements to occupy their intended space.
Fixing the Collapsed Parent
One of the most common symptoms of float-heavy layouts is the collapsing parent. This is
demonstrated in the example below:

Pellentesque habitant morbi tristique senectus et netus et malesuada


fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet,
ante. Donec eu libero sit amet quam egestas semper.

Notice that the bottom of the floated image appears outside its parent. The parent does not
fully expand to hold the floated image. This is caused by what we discussed earlier: the floated
element is out of the flow in relation to other block elements, so all block elements will render
as if the floated element is not even there. This is not a CSS bug; its in line with CSS
specifications. All browsers render the same in this example. It should be pointed out that, in
this example, adding a width to the container prevents the issue from occurring in IE, so this
would normally be something you would have to resolve in Firefox, Opera, Safari, or Chrome.
SOLUTION 1: FLOAT THE CONTAINER
The easiest way to fix this problem is to float the containing parent element:
Pellentesque habitant morbi tristique senectus et netus et malesuada
fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet,
ante. Donec eu libero sit amet quam egestas semper.

Now the container expands to fit all the child elements. But unfortunately this fix will only work
in a limited number of circumstances, since floating the parent may have undesirable effects on
your layout.
SOLUTION 2: ADDING EXTRA MARKUP
This is an outdated method, but is an easy option. Simply add an extra element at the bottom
of the container and clear it. Heres how the HTML would look after this method is
implemented:

<div id="container"> <img src="http://media.smashingmagazine.com/wp-


content/uploads/2009/10/lifesaver.jpg" width="200" height="222" alt=""
/> <p>Pellentesque habitant morbi tristique senectus et netus et
malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat
vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet
quam egestas semper.</p> <div class="clearfix"></div> </div>
And the resulting CSS applied to the new element:
.clearfix {
clear: both;
}
You could also do this by means of a <br /> tag with an inline style. In any case, you will have
the desired result: the parent container will expand to enclose all of its children. But this
method is not recommended since it adds nonsemantic code to your markup.
SOLUTION 3: THE :AFTER PSEUDO-ELEMENT
The :after pseudo-element adds an element to the rendered HTML page. This method has
been used quite extensively to resolve float-clearing issues. Here is how the CSS looks:
.clearfix:after {
content: ".";
display: block;
height: 0;
clear: both;
visibility: hidden;
}
The CSS class clearfix is applied to any container that has floating children and does not
expand to enclose them.
But this method does not work in Internet Explorer up to version 7, so an IE-only style needs to
be set with one of the following rules:
.clearfix {
display: inline-block;
}

.clearfix {
zoom: 1;
}
Depending on the type of issue youre dealing with, one of the above two solutions will resolve
the issue in Internet Explorer. It should be noted that the zoom property is a non-standard
Microsoft proprietary property, and will cause your CSS to become invalid.
So, because the :after pseudo-element solution does not work in IE6/7, is a little bit bloated
code-wise, and requires additional invalid IE-only styles, this solution is not the best method,
but is probably the best weve considered so far.
SOLUTION 4: THE OVERFLOW PROPERTY
By far the best, and easiest solution to resolve the collapsing parent issue is to addoverflow:
hidden or overflow: auto to the parent element. Its clean, easy to maintain, works in
almost all browsers, and does not add extra markup.
Youll notice I said almost all browsers. This is because it does not work in IE6. But, in many
cases, the parent container will have a set width, which fixes the issue in IE6. If the parent
container does not have a width, you can add an IE6-only style with the following code:
// This fix is for IE6 only
.clearfix {
height: 1%;
overflow: visible;
}
In IE6, the height property is incorrectly treated as min-height, so this forces the container
to enclose its children. The overflow property is then set back to visible, to ensure the
content is not hidden or scrolled.
The only drawback to using the overflow method (in any browser) is the possibility that the
containing element will have scrollbars or hide content. If there are any elements with negative
margins or absolute positioning inside the parent, they will be obscured if they go beyond the
parents borders, so this method should be used carefully. It should also be noted that if the
containing element has to have a specified height, or min-height, then you would definitely
not be able to use the overflow method.
So, there really is no simple, cross-browser solution to the collapsing parent issue. But almost
any float clearing issue can be resolved with one of the above methods.
Float-Related Bugs in Internet Explorer
Over the years, there have been numerous articles published online that discuss common bugs
in connection with floats in CSS layouts. All of these, not surprisingly, deal with problems
specific to Internet Explorer. Below, youll find a list of links to a number of articles that discuss
float-related issues in-depth:
The Internet Explorer Guillotine Bug
The IE5/6 Doubled Float-Margin Bug
IE7 Bottom Margin Bug
The IE Escaping Floats Bug
The IE6 Peekaboo Bug
The IE6 Ghost Text Bug
The IE6 Expanding Box Problem
The IE6 3-pixel Gap
Changing the Float Property with JavaScript
To change a CSS value in JavaScript, you would access the style object, converting the
intended CSS property to camel case. For example, the CSS property margin-left
becomes marginLeft; the property background-color becomes backgroundColor, and
so on. But with the float property, its different, because float is already a reserved word in
JavaScript. So, the following would be incorrect:
myDiv.style.float = "left";
Instead, you would use one of the following:
// For Internet Explorer
myDiv.style.styleFloat = "left";

// For all other browsers


myDiv.style.cssFloat = "left";
Practical Uses for Float
Floats can be used to resolve a number of design challenges in CSS layouts. Some examples are
discussed here.
2-COLUMN, FIXED-WIDTH LAYOUT
Roger Johansson of 456 Berea Street outlines an 8-step tutorial to create a simple, cross-
browser, 2-column, horizontally centered layout. The float property is integral to the
chemistry of this layout.
The layout consists of a header, a horizontal navigation bar, a main content column, a
sidebar, and a footer. It is also horizontally centered in the browser window. A pretty basic
layout, and not at all difficult to create with CSS once you know how to deal with the
inevitable Internet Explorer bugs.

Simple 2 column CSS layout


3-COLUMN, EQUAL-HEIGHT LAYOUT
Petr Stanicek of pixy.cz demonstrates a cross-browser 3-column layout, again usingfloat:
No tables, no absolute positioning (no positioning at all), no hacks(!), same height of all
columns. The left and right columns have fixed width (150px), the middle one is elastic.
3-Column Layout with CSS
FLOATED IMAGE WITH CAPTION
Similar to what we discussed earlier under Float in Practice, Max Design describes how to
float an image with a caption, allowing text to wrap around it naturally.

Floating an Image and Caption


HORIZONTAL NAVIGATION WITH UNORDERED LISTS
The float property is a key ingredient in coding sprite-based horizontal navigation bars. Chris
Spooner of Line25 describes how to create a Menu of Awesomeness, in which
the <li> elements that hold the navigation buttons are floated left:

How to Create a CSS Menu Using Image Sprites


To demonstrate the importance of the float property in this example, here is a screen shot of
the same image after using firebug to remove the float: left:

GRID-BASED PHOTO GALLERIES


A simple use for the float property is to left-float a series of photos contained in an
unordered list, which gets the same result as what you would see in a table-based layout.
Foremost Canadas product page (above) displays their products in grid-based format, next to a
left-column sidebar. The photos are displayed in an unordered list with the float property for
all <li> elements set to float: left. This works better than a table-based grid, because the
number of photos in the gallery can change and the layout would not be affected.

Paragon Furnitures futons page (above) is another example of a product page using an
unordered list with floated list items.
iStockphotos search results page (above) is a similarly-structured grid of photos, but this time
the photos are contained in left-floated <div> elements, instead of <li> elements.
ALIGNING AN <INPUT> FIELD WITH A BUTTON
Default styling on form elements across different browsers can be a pain to deal with. Often
times, in a single-field form like a search form, it is necessary to place the <input>element
next to the submit button. Here is a simple search form, with an image used for the submit
button:

In every browser, the result is the same: The button appears slightly higher than the input field.
Changing margins and padding does nothing. The simple way to fix this is to float the input field
left, and add a small right margin. Here is the result:

Conclusion
As was mentioned at the outset, without the CSS float property, table-less layouts would be,
at worst, impossible, and, at best, unmaintainable. Floats will continue to be prominent in CSS
layouts, even as CSS3 begins to gain prominence even though there have been a few
discussions about layouts without the use of floats.
Hopefully this discussion has simplified some of the mysteries related to floats, and provided
some practical solutions to a number of issues faced by CSS developers today.

3. Know Your Selectors


One of the keys to writing good clean CSS is to have a strong grasp of what CSS
selectors are available to you, how they work and the degree to which they are
supported on various browsers. It sounds like a simple enough topic, but in reality the
world of CSS selectors is quite complex.

There are a ton of different interesting things to learn about here, from using attribute
value selectors and targeting keywords in class names to how the universal selector
can be helpful for debugging your code. Even if you think you can personally get by
without understanding a bunch of fancy selectors, the truth is that other coders use this
stuff every day and you need to be able to understand what youre seeing when you hit
view source!

Resources To Get You There

CSS Selectors: Just the Tricky Bits


This is a fun article that takes a look primarily at the more complicated aspects of CSS
selectors. I skip the ground level stuff and jump straight into discussing how the concept
of the DOM translates to targeting various aspects of your document with CSS. Youll
learn all about selecting children and siblings, how to chain selectors and a lot more.

Like many self-taught CSS guys, my education was cobbled together from a million
different sources. I read articles, followed tutorials and experimented until my head hurt
to get to a point where I could bust out a complex layout and achieve the styling that I
want without too much trouble.
However, over time I slowly started to realize that I lacked a proper understanding of
one of the most basic, essential elements to working with CSS: selectors. Sure, I knew
how to target a class, ID or link, but I would often see snippets of code with selectors
that seemed completely foreign to me.

After writing these confusing coding practices off for so long I decided to really sit down
and learn about CSS selectors. It not only changed the way I code, it has drastically
helped me interpret and learn from CSS that others write.

I am certainly not the first to write about CSS selectors and this article will by no means
add anything revolutionary to the discussion. But if youre like me, a self-taught coder
with a mottled education, then this could just be the article that clarifies some of your
biggest confusions when you stare in wonder at the cryptic code of others.

Meet The Family

Before you learn about complex CSS selectors. You need to understand a few things
about HTML hierarchy. Youve heard these terms tossed around before but its time to
really think about them and make sure you grasp how they work.

The way we explain and refer to the structure of an HTML document is by using the
metaphor of a family tree. There are parents, children, siblings, descendants and
ancestors. To see what each means, lets use the simple code below.

1 <div id="example1">

2 <p>Wake Up Neo.</p>

3 <p>Follow the <a href="#">white rabbit</a>.</p>

4 </div>

Our div contains two paragraph elements and an anchor. All of these are descendants
of the div, which occupies the root position in this instance. A child is a direct
descendant of a parent. So in the example above, both paragraphs are children of the
div but the anchor is not. Instead, it is a child of the second paragraph.
Similarly, if we go back up the tree, the div has a differing relationship to the items. The
div is the parent of the paragraph tags but an ancestor of the anchor tag.
The final relationship is that of the siblings, also known as adjacent siblings. Just like in
your family, siblings share a parent. So in the example above, the two paragraphs are
siblings because the parent of both elements is the div. The anchor has no siblings
because it is the paragraphs only child.

Got That?

The family metaphor can get really confusing, but only if you over-think it. The
terminology is fairly intuitive and if you think about the literal meaning of the word, you
can pretty much guess what it means in HTML terms.

Just in case you still need a little more clarification, lets rewrite the example above with
content that explains the hierarchy of each element.

<div id="parentOfParagaphs"><!--Also an ancestor of the anchor-->


1
<p>Child of the div above, sibling to the paragraph below.</p>
2
<p>Child of the div above, sibling to the paragraph above and parent
3
sibling of none and descendant of the div.</a>.</p>
4 </div><!--Everything in the div is a descendant to the div-->

The Child Selector

Now that we understand how HTML works, we can start our discussion of CSS
selectors, which leverage this system. Armed with our knowledge of what an HTML
child really is, we can look at the CSS child selector.

The child selector is represented by the greater than symbol: >. Youve seen this in
CSS before but may or may not really understand how it works.

1 #someDiv > p {

2 color: blue;

3 }
This statement takes the paragraph tags that are children of the div and turns them
blue. Note that it only works for the children of that div, not necessarily all of the
descendants. Lets explore this further with the following example.
1 <div id="example2">

2 <p>First paragraph <a href="#">with a link</a>.</p>

3 <p>Second paragraph</p>

4 </div>

Lets say for some horrible reason we wanted to change that link color to yellow.
Obviously, we could target the link any number of ways, but were trying to learn about
the child selector so go with me. Lets see what happens if we implement this CSS:

1 div > a {

2 color: yellow;

3 }

Whoops, that didnt change anything! Thats because the link is not a child of the div, its
a child of the paragraph. So if we change that code to target any anchors that are
children of paragraphs, we achieve our goal.

1 p > a {
2 color: yellow;

3 }

Order

Now that you understand how the child selector works, keep in mind that, as with all
CSS, the order makes a big difference. To illustrate this, lets start with this basic HTML
structure:

1 <div id="example3">
2 <p>First paragraph</p>

3 <p>Second paragraph</p>

5 <div id="nestedDiv">

6 <p>Third paragraph</p>

7 </div>

8 </div>

Now lets consider the following two CSS snippets. They look similar, but are very
different!

1 #example3 p {

2 color: red

3 }

4
5 #example3 > p {

6 color: blue

7 }

1 #example3 > p {

2 color: blue

3 }

5 #example3 p {

6 color: red

7 }

The first snippet, makes all of the paragraphs to red, then changes only the children of
the root div to blue.

The second snippet does the opposite, it initially targets the first divs child paragraphs
and turns them to blue but then changes all of the paragraphs to red. This of course
results in three red paragraphs.
The second example breaks an important rule in CSS: go from general to specific, not
the other way around. Since we started with a specific selector setup that targeted only
two paragraphs and then moved to a general selector that targeted all of the
paragraphs, the second completely overruled the first!

Chaining

If you really want to go nuts, you can chain child selectors together. In the following
example, I first targeted any children paragraphs of the example3 div and changed them
to blue, then I targeted any paragraphs that were the children of divs that
were also children of another div and changed those to red.

1 <div id="example3">
2 <p>First paragraph</p>

3 <p>Second paragraph</p>

5 <div id="nestedDiv">

6 <p>Third paragraph</p>

7 </div>

8 </div>

1 #example3 > p {

2 color: blue;

3 }

5 div > div > p {

6 color: red;

7 }
The Adjacent Sibling Selector

With child selectors all squared away we need to learn how to target siblings. The
adjacent sibling selector is represented by the plus symbol: +. With it, we can target
any element that is a sibling of any other element. Heres an example:

1 <div id="example4">
2 <p>First paragraph</p>

3 <p>Second paragraph</p>

4 <p>Third paragraph</p>

6 <div id="nestedDiv">

7 <p>Fourth paragraph</p>

8 </div>

9 </div>

1 p + p {

2 color: red;

3 }
In our CSS, we used the adjacent sibling selector, which changed the second and third
paragraph to red. This is very tricky isnt it? instinctively, we would expect the first
paragraph to be red as well. After all, the first paragraph is on the same level of the tree
as the next two and has siblings. However, this selector only applies to elements that
are preceded by something else. In this instance, only those paragraphs preceded
directly by a sibling paragraph will be targeted. The first paragraph in the list is preceded
by the div, so it isnt changed.

With this in mind, the following code would change the background of the nested div to
gray because it is indeed preceded by a paragraph.

1 p + div {

2 background: gray;

3 }

Further Chaining

Just as with child selectors, you can chain adjacent sibling selectors. The system works
exactly the same as before. You can also combine the two for an added layer of
complication. Heres where our CSS really starts to look strange.

1 <div id="example5">

2 <p>First paragraph</p>

3 <p>Second paragraph</p>

5 <div id="nestedDiv">
6 <p>Third paragraph</p>

7 <p>Fourth paragraph</p>

8 </div>

9 </div>

1 div > p + p {

2 color: red;

3 }

In this example, we targeted paragraphs that were children of divs that were also
preceded directly by another paragraph.

The Almighty Asterisk

The final piece of confusing CSS that I want to go over is the worst yet: the asterisk. Did
you know that, depending on the context, the asterisk can refer two completely different
things?

Universal Selector

The first example of an asterisk in CSS is the one youre probably the most familiar with:
the universal selector. True to its name, this selector targets any and every element on
the page. We typically see it used in CSS resets. The following resets the padding and
margin on every element.

1 * {margin: 0; padding: 0;}


You can take this further and achieve some really interesting results. For instance, the
following turnsevery element inside a div red, this includes items like links that have a
default color set to something else and wouldnt be affected by simply targeting the div.
1 #someDiv * {

2 color: red;

3 }

Further, this snippet targets grandchild paragraphs of the div, but not direct child
paragraphs.

1 div * p {

2 color: red;

3 }

You can take this as far as you want, the following targets the great grandchildren of the
div. You can see this chaining method used frequently in CSS debugging tricks.

1 div * * p {

2 color: red;

3 }

Arbitrary Substring Attribute Value Selector

Now with CSS3, the asterisk can also be used to implement the arbitrary substring
attribute value selector, you can pull that title out when talking to other developers if
youre trying to look smart.

The following code targets any div with the word section in the title. It can be
section3 or section-Four, it doesnt matter, as long as it contains the indicated string,
the subsequent styles apply.

1 div[id*='section'] {color: red;}

This code would apply to all of the divs in this HTML:


01 <div id="section-1">
02 </div>

03

04 <div id="section-2">

05 </div>

06

07 <div id="section-3">

08 </div>

09

10

11 <div id="section-4">

12 </div>

Attribute Selectors

That last curve ball that I threw you was an example of an attribute selector. In CSS3,
attribute selectors are so complicated that they merit their own article! Fortunately for
you, we have a piece on that very topic.

CSS Attribute Selectors: How and Why You Should Be Using Them
If youre a nerd like me, this is a really fascinating topic. Its amazing to see all of the
selector tools that you have at your disposal.

Pseudo Class Selectors

This is yet another selector topic that you should familiarize yourself with, and once
again it really does merit a thorough inspection of the topic. As with just about every
CSS topic known to man, CSS-Tricks has you covered.

Meet the Pseudo Class Selectors

Conclusion
With CSS, theres almost always more than one way to target something. In fact, theres
often half a dozen ways. For any of the examples above, you can probably name a
quicker way to target what we were shooting for, but as you familiarize yourself with the
DOM, these selectors really do start to come in handy.

Even if you never find yourself in need of them, its vitally important to understand them
because you willsee them projects that you collaborate on, frameworks that you
download, tutorials that you read and any other place that you regularly find code.
Understanding HTML element relationships and their corresponding CSS selectors can
only make you a better coder!

The 30 CSS Selectors you Must Memorize


Jeffrey Way is a web dev rockstar and articles like this prove why. This Nettuts+ article
covers a vast array of CSS selectors in a simple and brief format that places a lot of
emphasis on browser support. Amazingly enough, Jeff even coded up live example
pages for each of the thirty selectors.

CSS Attribute Selectors: How and Why You Should Be Using Them
Attribute value selectors are one of the most powerful subsets of CSS selectors, and
CSS3 really boosts that power. You wont believe how versatile your selectors can
become with a little attribute value magic. After reading this article, youll be slinging
around phrases like arbitrary substring attribute value selector like a pro.

HTML Attributes

Before I introduce you to the concept of CSS attribute selectors, you should know what
an HTML attribute is. The good news is, youre already familiar with several of
them: class, id, style, and href for example. There are a ton more though, check
out W3.org for a complete list.
CSS makes styling some attributes easy. For instance, if we want to style an id or class,
we just use the following.
1 #someid {color: black}

2 .someclass {color: black}


This is all well and good, but what if we want to style some other attributes? This is
where attribute selectors come into play.

Attribute Selectors

As we just learned, attribute selectors are exactly what they sound like, a way to select
and target specific attributes using CSS. This is actually really easy to do and just
involves a set of brackets containing the HTML that you used. Lets see how this works
by looking first at some basic HTML.

1 <ul>

<li><a href="http://designshack.net/">Design Shack</a></li>


2
<li><a href="http://www.smashingmagazine.com/">Smashing
3
Magazine</a></li>
4
<li><a href="http://sixrevisions.com/">Six Revisions</a></li>
5 </ul>

Lets say I wanted to target and style only the Design Shack link. I could use pseudo
selectors, but this assumes the list stays in that order and browser support isnt the
best. Instead, what we can do is use an attribute selector to target the specific href
that were interested in.

1 a[href='http://designshack.net/'] {color: blue;}

Repeating Attributes

Another example thats used a lot is a list of contacts, one or more of which should be
styled a certain way. Using attributes, we can differentiate between friends and
contacts.
1 <ul>
2 <li><a href="#" rel="friend">Larry</a></li>

3 <li><a href="#" rel="contact">Curly</a></li>

4 <li><a href="#" rel="contact">Moe</a></li>

5 <li><a href="#" rel="contact">Curly Joe</a></li>

6 <li><a href="#" rel="friend">Shemp</a></li>

7 </ul>

We can then go in and style each of these rel attributes differently using the same
syntax as above. Much like with a class, multiple items can meet the criteria in one
declaration.
1 li a[rel='friend'] {font-weight: bold;}

2 li a[rel='contact'] {font-weight: 200;}

Using this code we can achieve the results below. Notice that even if we start adding in
new contacts to the top of the list, these selectors will still work where :nth-
child wouldnt. Pretty cool right? Further, just about every current browser supports
these, including IE back to version 7!

Its also important to note that you dont have to be so specific. The following will
style any element with a rel attribute applied.
1 li a[rel] {font-weight: bold;}

Handling Multiples Values

The tricky part about using Attribute selectors is that they get a little funny when there is
multiple attributes. Consider the following tweak to our previous list.
1 <ul>

2 <li><a href="#" rel="friend nofollow">Larry</a></li>

3 <li><a href="#" rel="contact">Curly</a></li>

4 <li><a href="#" rel="contact">Moe</a></li>

5 </ul>

You would think that styling the first list item would be the same process considering it
still has friend in it, but thats not the case. Simply using =friend wont successfully
target this anymore. Instead, we have to use the following, which looks for friend as
one of the rel values.
1 li a[rel~='friend'] {font-weight: bold;}

This will result in the Larry list item being bolded where as the
previous a[rel='friend'] syntax wouldve missed it.

CSS3 Attribute Selectors

CSS3 has given us so many cool new toys and tools to play with. Its no surprise then
that there are also some new Attribute Selectors that help us bring even more specificity
into our targeting. Lets start with my favorite.

Styling Similarly Named Attributes

This is where things get awesome. Lets say you had the following HTML and that you
wanted to target only the upperSection and lowerSection, how would you do it?

01 <div id="upperSection">

02 <p>Lorem ipsum dolor sit amet...</p>

03 </div>

04

05 <div id="somethingElse">

06 <p>Lorem ipsum dolor sit amet...</p>


07 </div>

08

09 <div id="lowerSection">

10 <p>Lorem ipsum dolor sit amet...</p>

11 </div>

12

13 <div id="footer">

<p>Lorem ipsum dolor sit amet...</p>


14
</div>
15

One easy answer is the new Arbitrary Substring Attribute Value Selector, or the really
cool little asterisk thing. Since the two divs that we want to target both contain Section
in their names, we can easily target them.

1 div[id*='Section'] {color: red;}

I was blown away by this. Here were using CSS to actually dig through our ID names to
find specific values within a larger name and target those elements. This opens up a lot
of possibilities and makes complex targeting with little markup a much easier task.

Beginning and Ending

While the Arbitrary Substring Attribute Value Selector will target a given string
anywhere, the Beginning and Ending versions allow rarer cases to be handled where
you only want the first or last item to be considered.

1 <ul>

2 <li><a href="#" title="stooge one">Larry</a></li>

3 <li><a href="#" title="the second stooge">Curly</a></li>

4 <li><a href="#" title="stooge three">Moe</a></li>

5 <li><a href="#" title="impostor">Curly-Joe</a></li>


6 </ul>

Lets say we want to target all the stooges, making Larry and Moe red and Curly yellow.
To do this, we can insert use [title^='stooge'] to grab all those with stooge as the first
word and [title$='stooge'] to grab all those with stooge as the last word.
1 li a[title^='stooge'] {color: red} /*Beginning*/

2 li a[title$='stooge'] {color: yellow} /*Ending*/

Chaining Attribute Selectors

Lets say you want to get super specific and add on multiple criteria. Thats as simple as
chaining together multiple attribute selectors. Lets see how this works with the HTML
below.

1 <ul>

2 <li><a href="#" title="stooge one">Larry</a></li>

3 <li><a href="#" title="the second stooge">Curly</a></li>

4 <li><a href="#" title="stooge three">Moe</a></li>

5 <li><a href="#" title="the impostor">Curly-Joe</a></li>

6 </ul>

Now, lets target any link with stooge in the title, but only those beginning with the.
Notice that we dont want to casually target the because this also appears in the last
item. Heres the syntax for achieving this:

1 li a[title*='stooge'][title^='the'] {color: red;}

Simple right? All we did was take the two rules that we needed and put them on the
same line. Its important to note that this isnt an either/or scenario but a both/and. Only
those items that meet both criteria will be changed.

Further Reading

If youre enough of a nerd that youre just loving attribute selectors, there are two more
sources that I highly recommend that you check out.
CSS Tricks
First, Chris Coyier has a very thorough introduction over at CSS Tricks covering much
of the same content that we covered here. Chris is a CSS super genius though and
likely explains them much better than me!
The Book of CSS3
Next, check out Peter Gasstons The Book of CSS3, which has been my main reference
for all things CSS3 lately. I simply cant get enough of this book and have given it quite
the permanent position on my desk! Gasston adds to this conversation with a
discussion of General and Adjacent Sibling Combinators, which are another interesting
way to target certain elements. Take the following HTML as an example:

1 <div id="combinators">
2 <p>Not this one.</p>

3 <h1>Gibberish</h1>

4 <p>Pick me!</p>

5 <p>Lorem ipsum dolor sit amet...</p>

6 <p>Lorem ipsum dolor sit amet...</p>

7 <p>Lorem ipsum dolor sit amet...</p>

8 </div>

Now, lets say we wanted to target only the Pick me! paragraph. The Adjacent Sibling
Combinator lets us do just that. The following code targets any p tags immediately
preceded by an h1 tag. There is only one of these in the example above (the first
paragraph after the header).
1 h1 + p {color: orange;}

Similarly, the General Sibling Combinator will allow us to target all of the p tags that
come after the header. So that first paragraph wont change color, but all of the others
will.
1 h1 ~ p {color: orange;}

This is just a taste, for more information on these, check out The Book of CSS3.
Browser Support

As I mentioned briefly above, as far as I can tell, youre pretty covered on most of these
techniques back to IE7 with all major current browsers rocking perfect support.
However, its not exactly a full score across the board with some of the lesser-known
browsers being a little spotty. You can find a nice little table of browsers and their
support for all of this stuff and more at dev.l-c-n.com.

Conclusion

To be honest, I very recently knew little to nothing about CSS attribute selectors. After a
little bit of research though I was stunned by how cool they are and baffled as to why
they seem to be so rare (browser support is better than for a lot of the stuff we mess
with). With just a little bit of code, you can achieve remarkably specific targeting with
little to no additional markup required.

4. Learn DRY Coding Concepts

Dont Repeat Yourself. This simple phrase has drastic implications when it comes to
coding. When you really dive into DRY coding practices, the result is cleaner code, less
work and a beautiful new workflow that is as empowering as it is flat out awesome.

Unlike the other topics above, which are fairly narrow, this one is a pretty vast subject
that covers all manner of different practices, techniques and ideas. Interestingly enough,
one of the things that has recently gotten my mind focused on DRY coding practices is
the use of CSS preprocessors.
Though many claim that preprocessors lead to poor coding practices, the reality is the
opposite. Obviously, preprocessors themselves help avoid manual repetition, but it goes
beyond that. Examining the output of tools like LESS and SASS and the goals for the
languages in general has actually led to me writing better pure CSS! Once you master
concepts like @extend in Sass, you cant help but think about the implications when
youre coding with only CSS.

Resources To Get You There

DRY CSS: Dont Repeat Your CSS


In this article, Steven Bradley introduces you to the topic of DRY CSS and covers some
of its main principles and goals. He boils the practice down to three simple ideas and
shows you how to implement these ideas in a real workflow. The concepts are largely
borrowed from a Jeremy Clarke presentation covering the same topic.

A few weeks ago in the comments on my post about css formatting, Brett and
David pointed me to a couple of articles and a presentation I hadnt yet seen. All had
interesting ideas about css practices and I thought I would offer some of my thoughts
on them.

One of the articles, Dont use IDs in CSS selectors?, makes the argument for using
classes over IDs as css styling hooks. Since I covered another article with similar of
arguments I wont cover Olis article here, but would recommend you give it a read.
In this post I want to talk about a presentation Brett pointed me to. Ill get to the
article David pointed me to next week. The presentation is one give by Jeremy Clarke
on the topic of DRY CSS.
DRY CSS Principles
I wasnt quite sure what to make of Jeremys presentation. Ive seen some of his
other presentations and generally like both Jeremy and his ideas. Hes certainly worth
listening to. While I agree with the basic principle of dont repeat yourself, I found
myself unsure of the methods set out in the presentation and if they really solved the
problem were trying to solve.
Some of my doubt is probably due to a lack of practical application on my part so
keep that in mind. Let me walk you through Jeremys DRY ideas and then point out
what I did and didnt like about them.

If youre not familiar with DRY, it stands for dont repeat yourself, which is
hopefully something we can all get behind. Its why we want variables and functions.
Many are moving to css preprocessors for this reason though Jeremy doesnt seem to
care for them He suggests they lead to destandardization and dependence on external
libraries. Im not sure either is really true.
Jeremy offered 2 principles for writing good css.

-Keep style separate from content

-Avoid specificity by harnessing the cascade

These should look familiar as theyre essentially the same principles of OOCSS
and SMACSS. However Jeremy sees IDs and classes a little differently. He thinks IDs
are fine for styling hooks and that both should be named based on the content as
opposed to how the content looks.

This goes against what Oli says in the article linked to above and the one I
covered a couple weeks back by Nocolas Gallagher, both of whom say its fine and
preferred to name classes after how an object looks and suggest we skip using IDs for
styling hooks.
So how does it work?
How DRY CSS Works
DRY CSS comes down to 3 things:

Group reusable css properties together


Name these groups logically
Add your selectors to the various css groups
Each group should be defined by shared properties. For example one group
might describe the background color and border color for a content box used
throughout your design while another might describe a consistent set of type
characteristics used throughout your design.
Each property/value pair should be defined only once, though in his code examples
Jeremy does repeat pairs. Each group would also get multiple selectors. I think this
makes more sense with an example and heres one Jeremy used in his presentation.
Group reusable properties Below were simply grouping a couple
ofbackground and border colors that would be used in a number of places across the
site.
1{
2 background-color: #fff;
3 border-color: #ccc;
4}
5
6{
7 background-color: #fff;
8 border-color: #bbb;
9}
Name groups logically Im not sure these are great names and Jeremy was quick
to point out they could be better, but hopefully you get the idea.
1#LIGHT-WHITE-BACKGROUND,
2.light-white-background
3{
4 background-color: #fff;
5 border-color: #ccc;
6}
7
8#MEDIUM-WHITE-BACKGROUND,
9.medium-white-background
10{
11 background-color: #fff;
12 border-color: #bbb;
13}
The all caps ID is to make this block of code easier to find in Firebug, which doesnt
show comments. The lower case class at the end is to enclose the selectors that will
later be in between and to make it less likely you forget the commas at the end of all
but the last selector rule. I wasnt crazy about creating extra IDs and classes that
really exist for a lone developer tool. Id prefer comments above and below the
group.

Add selectors to various groups With groups defined and named, you add all
the selectors that need to be displayed with the property/values of the group.
1#LIGHT-WHITE-BACKGROUND,
2.translation,
3.entry .wp-caption,
4#full-article .entry img,
5.recent-comment .comment-text,
6.roundup h3,
7.post-header-sharing,
8#post-categories td.label,
9#post-archive roundup h3,
10.subscription-manager ol,
11.light-white-background
12{
13 background-color: #fff;
14 border-color: #ccc;
15}
16
17#MEDIUM-WHITE-BACKGROUND,
18textarea:focus,
19input:focus,
20#author-email-form .input-focus,
21#respond p input:focus,
22.wpfc7 input:focus,
23.medium-white-background
24{
25 background-color: #fff;
26 border-color: #bbb;
27}

The above is a simplistic example for the sake of demonstration. The general idea is to
think in terms of style patterns. You have a box in your design that holds content. You
write the styles necessary to create it visually and place them together in a group. You
give the group a name, and then add the css selectors that will visually be displayed
using the pattern.
One of the questions I immediately had was would all these selectors really be
needed? What advantage does this offer over having each group be a class thats
added where needed in the html. Sure it would reduce the need for classes, but is that
a bad thing?

Ive mentioned a few times in recent posts that its really about coupling and have
pointed to some articles showing how a class couples css and html less than the
descendent selectors that are being used here.
Additional Thoughts
Throughout the presentation Jeremy mentions some of the benefits of his
DRY approach. Here are a few of them along with some of my thoughts

It encourages you to think in terms of style patterns (groups) rather than


individual objects. I agree. I think this is a good goal and is also encouraged
by OOCSS and SMACSS
The naming of groups encourages rational organization of design. Im not sure
about this. The examples didnt feel all that organized to me with so many
selectors in each group. I think it would make it more difficult to find the
selector you want.
It encourages optimization and generalization of selectors. Again good goals
and I think DRY CSS would help accomplish this.
It doesnt require changes to html. True to an extent, but is this really more
beneficial? I no longer thing so, though I know many do.
There shouldnt be any performance issues. I think wed be dealing with
whatever performance issues we deal with now as part of using descendent
selectors. I think jeremy quickly glossed over any potential downside here,
though I dont know that css selector performance is something most of us need
to be overly concerned with.

DRY and OOCSS


Jeremy tried to show how DRY and OOCSS were compatible. He points out that the
basic principles of both are mostly the same and that you can group styles in a way
that adheres to OOCSS ideas. Im not so sure this is true as the use of decedent
selectors goes against OOCSS. Essentially DRY is replacing a single class with a
variety of descendent selectors so as not to have to alter the html.
In the case of DRY when you want to change the style of a content box, youd cut
and paste its selector in the css from one group to another. In OOCSS youd change
a class name in the html. In either case you might need to define or redefine some
styles.

Is one approach better than the other? To me using classes as in OOCSS seems a lot
cleaner, easier to read, and more flexible. Ive also become convinced that classes
reduce coupling which is the real enemy here.

However if youre someone who disagrees and thinks adding classes everywhere is
the wrong approach you might want to give DRY CSS a look as it offers many of
the same advantages of OOCSS in a different way.

Without having used either in practice to any great degree its hard for me to
authoritatively state one approach is better than the other, though my sense is
OOCSS is the better approach. Again Im convinced that classes reduce coupling
and are preferred. I also think OOCSS more readable.

Summary

Overall I think the basic ideas behind DRY CSS make sense. Dont repeat yourself is
a good general principle to follow and eliminating duplication of css code should
naturally be part of that.

DRY CSS shouldnt be too hard to understand if you followed the example code
above. Create the groups, name them, and then add the selectors.
The main difference I can see between DRY and either OOCSS and SMACSS is that
the first continues to use the same descendent selectors weve been using for years,
while the latter two ask us to make greater use of classes. I think the class approach
the better one and so I probably wont be using DRY CSS in practice.

Not everyone agrees with the class approach though, and if youre one of those
people then I think you might enjoy DRY CSS. It aims trying to achieve the same basic
goals of the class based approaches. I can certainly see the appeal of writing css this
way.

An Introduction To Object Oriented CSS (OOCSS)


As I mentioned before, the ideas inherent in the DRY CSS movement are pretty far
reaching and directly related to concepts in other constructs. OOCS is an increasingly
popular methodology that aims to help you create faster, more efficient stylesheets with
superior organization and less repetition. There are two main principles at work in
OOCS: separation of structure from skin and separation of containers and content. This
article from Smashing Magazine will walk you through the basic ideas and help you
apply them to your own work.

An Introduction To SMACSS Guidelines For Writing CSS


Remember Steven Bradley from the first article on DRY CSS? He also wrote this piece,
which explains a project thats similar to but separate from OOCS: SMACSS (a project
from Jonathan Snook). As with OOCSS, SMACSS has two main goals. The first is to
increase the semantic value of a section of HTML and content, and the second is to
decrease the expectation of a specific HTML structure. This article explains both goals
in detail and provides helpful code examples so you can see SMACSS in action.

In recent weeks Ive been discussing ideas and approaches to writing css. Ive looked
at abstracting css and talked in some detail about Object Oriented CSS. If classic css sits
on one side of an approach to writing css and OOCSS sits on the other, SMACSS sits
somewhere in the middle.
While Ill do my best to cover the basics here, Id recommend reading through
theSMACSS documentation. Its not a long read and of course it is the original source.
You can also listen to SMACSS creator, Jonathan Snook, talk about it on the premiere
episode of the ShopTalk podcast.
As with my OOCSS post, this one is more research on my part than any actual
practice.

What is SMACSS?

SMACSS stands for Scalable and Modular Architecture for CSS and it has 2 core
goals.

Increase the semantic value of a section of html and content


Decrease the expectation of a specific html structure
Like Object Oriented CSS, SMACSS is an approach to writing css and html with
more emphasis placed on using classes. Unlike OOCSS, it doesnt suggest using
classes for everything. Its fine with IDs and descendent selectors where appropriate.

At the very core of SMACSS is categorization. By categorizing CSS rules, we begin to see
patterns and can define better practices around each of these patterns.
Much like OCCSS, the purpose of this categorization is less code repetition, a more
consistent experience, and easier maintenance. Under SMACSS there are 5 general
categories of css rules.

Base These are your defaults (html, body, h1, ul, etc)
Layout These divide the page into major sections
Module These are the reusable modular components of a design
State These describe how things look when in a particular state (hidden or expanded,
active/inactive)
Theme These define things like a color scheme or typographic treatment across a site
Most of us tend to mix styles across all of these categories, which creates complexity.
If instead, we can understand the differences in these categories and apply some
guidelines to each we can simplify our css.

Jonathan offers a naming convention for working with SMACSS, though hes quick
to point out you dont need to follow his convention. He does feel that having some
consistent naming convention is important.
Base Nothing needed
Layout l- or layout- prefixes
State is- prefix as in is-active or is-hidden
Module Modules just use module name ( .callout ) instead of trying to prefix each,
however related modules receive a consistent prefix to help organize them
Lets dig a little deeper into the guidelines for each of the categories.

Base Rules
Base rules are applied directly to elements through element selectors, descendent
selectors, child selectors, pseudo-classes, however not specific class or ID selectors.

As the name implies these are the base or default styles for elements. CSS resets are
an example of base styles. Base styles are pretty simple and probably arent much
different than what you already do under classic css.
Layout Rules
There are major and minor layout components in every design. A header block
would be a major component, while the combination of logo and tagline within the
header would be a minor component. The layout rules of SMACSS apply to major
components. Minor components fall under the module rules well get to
momentarily.

The amount of reuse can also determine which blocks are major and minor parts of
the layout. More repetition should lead you to think module over layout and classes
over IDs. However, SMACSS doesnt limit IDs to behavioral hooks. It sees them
more in traditional css terms. Single use calls for IDs. Multiple uses call for classes.

Generally a layout style will have a single selector (either an ID or class).


Additionally there could be a style set to allow the layout style to respond to
different factors.

1 #sidebar { width: 20%; }


2 .l-fixed #sidebar { width: 250px; }
The above would allow for a change between flexible and fixed layouts.

Jonathan walks through an example from a Featured section on CNNs website, which
is worth looking over in more detail. The html for the section is as follows:
1 <div>
2 <h2>Featured</h2>
3 <ul>
4 <li><a href=""></a></li>
5 <li><a href=""></a></li>
6 </ul>
7 </div>
and the corresponding css:

1 div#featured ul {
2 margin: 0;
3 padding: 0;
4 list-style-type: none;
5 }
6
7 div#featured li {
8 float: left;
9 height: 100px;
10 margin-left: 10px;
11 }
Familiar stuff and probably similar to html and css youve written before. There are
3 assumptions with the above code.

there will only ever be one featured section on page


list items in the section are always floated to the left
list items in the section always have a height of 100px
These assumptions might be reasonable for small sites, but become less reasonable
as sites grow larger and more and different people work on them. SMACSS
guidelines would instead suggest the following css after adding the l-grid class to
the container div.

1 .l-grid {
2 margin: 0;
3 padding: 0;
4 list-style-type: none;
5 }
6
7 .l-grid > li {
8 display: inline-block;
9 margin: 0 0 10px 10px;
10 }
Theres an additional IE7 hack on ,l-grid > li, which I havent shown here. According
to Jonathan, the SMACSS styles improve things because:

The grid layout can now be applied to any container to create a float-style layout
The depth of applicability has been decreased by 1 (more on this below)
The specificity of the selectors has been reduced
The height requirement has been removed allowing each row to grow to the height of its
tallest item.
Module Rules
Again modules are built around minor page components like navigation bars and
widgets. They tend to be inside layout components and even within other modules.

Modules should be designed so they can exist on their own, which gives them
greater flexibility in being combined and moved around to different parts of the
design without breaking the layout. With modules we do want to avoid IDs and
element selectors. More reuse means classes.

Where you can reasonably predict what html elements will be used its ok to use
descendent selectors as in .module span, but as projects grow things will quickly
become less predictable and so it becomes limiting to attach element selectors to
module classes. The more generic the html selector (such as div or span), the more
likely there will be a conflict.
Subclassing Modules
Modules are for reuse and naturally well want to reuse modules in different
sections of our layouts When we do, we might reach for the parent element to modify
the style.

.box { width: 200px; }


1 .box ul { width: 100px; }
2 #sidebar .box ul { width:
3200px; }
This can quickly lead to specificity issues. Better would be to subclass the box module
and apply the subclass.
.box { width: 200px; }
1 .box-contstrained { width:
2100px; }
With sub-classing both the base module and the sub-module class names get applied
to the html element (Presumably there would be more styles on the base module than
shown here). As we saw with OOCSS we want to avoid css based on location and
subclasses help us stay away from location based css.

State Rules
A state style is one that augments or overrides other styles under given conditions.
For example an accordion with collapsed and expanded states. These are typically
applied to the same element, should be built to stand alone, and are usually
developed on a single class selector.

Jonathan presents a more complete example of a calendar structured in html as a


table. Heres Ill simply present 3 selectors to show the main idea behind state rules

.cal td { }
1 .cal td.cal-today { } /* overrides the default for a specific cell
2*/
3 .is-selected td { } /* overrides the default for a state change */
State changes are represented in one of three ways:
Class name The change happens by adding or removing a class, usually with
Javascript
Pseudo-class The change happens to elements that are descendants or siblings of the
element with the pseudo-class
Media query The change happens under defined criteria, such as different viewport
sizes.
Theres a lot more detail on the SMACSS site, which Ill again encourage you to read. I
would like to point to a couple of things Jonathan says about changing states, which I
found interesting.
When you actively ask yourself, what is the default state, you find yourself thinking
proactively about progressive enhancement
He closes the SMACSS section on changing state with:

Thinking about your interface not only modularly but as a representation of those
modules in various states will make it easier to separate styles appropriately and build
sites that are easier to maintain.
More than anything I think both SMACSS and OOCSS are about getting us to
rethink our css practices and its this thought, above any specific guidelines and rules,
that will prove to be the most valuable take away.

Theme Rules
Theme rules are similar to state rules in that they describe how layout and modules
might look. However, they arent used as often within a single project and so Jonathan
doesnt consider them as part of the core types.

Theme rules would define colors or typography across a site and separating themes
into their own set of styles can allow them to be more easily modified. If you
remember this concept of being able to change all color styles to create a new color
scheme or simply experiment while learning is what led me into all this recent css
exploration in the first place.
Depth of Applicability
One of the things that comes up with greater emphasis on classes is the coupling
between css and html. Its something I mentioned previously when talking aboutour
flawed css practices. Is this coupling really about our use of classes over element
selectors or is something else at play?
#sidebar div { border: 1px solid
#333; }
1 #sidebar div h3 { margin-top: 5px; }
2 #sidebar div ul { margin-bottom:
3 5px; }
The above relies on a specific html structure
There is a greater depth of html selectors than necessary
Its more this depth of applicability (the number of generations affected by a
given rule) that increases coupling.

Consider the html below.

body.article > #main > #content > #intro > p > strong
1 {}
The depth of applicability is 6 generations. Even if the the selector is written as
.article #intro strong, the depth is still the same 6 generations.

The greater the depth, the greater the dependency on a given html structure. This
is what strongly couples html and css and is what wed like to avoid. It means page
components cant be moved and that more duplication of code is likely.

A greater use of classes ultimately reduces the depth of applicability, leading to


more flexible styles. It may seem counterintuitive as were adding extra markup to
html with classes, but this frees us from relying on specific html structures.

p.module > strong


1 {}
Above the module class could be added to any paragraph, reducing depth and
increasing flexibility.
Closing Thoughts
As I mentioned with OOCSS let me remind you again that what you see here is
based on research and not actual practice. In the coming weeks Id like to take a
simple layout coded in classic css and recode it under both OOCSS and SMACSS
guidelines to gain a little more perspective from real practice.

Doug Avery of Viget, posted some thoughts about both a few months back based on
actual use. Its a good read to understand some of the pros and cons and differences
between classic css, SMACSS, and OOCSS.
Both OOCSS and SMACSS share some common goals and try to help us write
more flexible and maintainable css.

I havent quite wrapped my head around either yet, though both make sense to
me as a better approach to writing css. Both urge us to make better use of classes.
SMACSS pulls back some from using classes for everything, reserving them mainly
for modules and states.

This is still exploration for me. My early guess is that while I like the ideas behind
both OOCSS and SMACSS, Ill ultimately settle on something of my own creation
based heavily on the same underlying principles. Its the underlying principles Im
most interested in.

I also get the feeling that once Ive spent more time with css preprocessors the
whole picture of a new approach to css will become clearer to me.

5. Know Your Browser Support


The fifth and final key to improving your CSS is to know what works where. CSS3 is far
too enticing for most of us to ignore, but the hard truth is that a whole bunch of it doesnt
work in certain browsers (by certain browsers I of course mean IE).

The big secret that newbie web developers need to get into their heads is not that they
need to memorize every single CSS feature and how every browser known to man
handles it, instead its that there are absolutely amazing resources available to you that
give you this information freely, you just have to know where to look.

Resources To Get You There

Nailing Browser Support in CSS3 and HTML5: Invaluable Resources to Use Today
In this article I introduce you to the relatively few sites that I have bookmarked for
checking browser support. These resources are fantastic, visual and give you the
information you need in a jiffy so you can get back to coding. Take a look to see what
they are!
Browser Support for CSS3: Whats the Current Status?
This article was written over a year ago so the current status piece is arguable, but not
enough has changed in this time to make the information in this article obsolete. It
serves as an incredibly helpful overview of various CSS3 properties, divided into
sections based on what works everywhere and what you need to watch out for. Itll only
take you a few minutes to go through and its well worth the read.
The Importance of Cross Browser Compatibility: Tips and Resources
If youre really new to CSS and need a basic introduction to the topic of browser
compatibility and why its important, this Noupe article has you covered. More than
merely selling you on the idea of compatibility, it lists a bunch of great resources that
you can use to ensure maximum compatibility. Of particular interest is the list of tools
that will help you test your site in various browsers.

Im Supposed To Read All This in 24 Hours?

Ive presented you with five absolutely critical topics to study up on and no less than
fifteen articles from which you can learn the principles that you need to know. This is all
well and fine but in my title I promised that youd get better in a single day and not
everyone has the time to sit down and read fifteen long articles!

The good news is that I gave you three articles on each topic so youd have some
variety to choose from. I explained the contents of each in detail so you can select the
one that best fits your needs. Remember to choose the articles to read not based on
what you do know, but what you dont know. Make it a goal to fill the gaps in your
knowledge.

My suggestion is to browse through the content above and pick five articles to read
(one from each section). Even thats a lot to undertake in a day but most of them arent
too much more than a thousand words or so, many are less. Im confident that you can
pull it off. If you cant, no problem. Change your goal to improving your CSS skills in a
week and read one of your five chosen articles every day for the next five days. I
guarantee that come next week youll be much better at writing clear, concise,
compatible and reusable CSS.

What Other Concepts Do You Recommend?

Now that youve read my top five topics that people should brush up on to improve their
CSS skills, I want to hear from you. What other topics do you think CSS coders typically
struggle with and what resources do you recommend for anyone looking to learn more?

You might also like