Posts Filed Under ‘Basic Techniques’
Build an American Flag out of XHTML and CSS
I’d like to wish a very happy 4th of July in advance to all the loyal, lovely, learning readers of CSSnewbie. To celebrate our upcoming Independence Day (because I am a Yankee), I took a bit of time and created the CSS and XHTML USA flag you see above. Visage above is but an image, but here it is again in an iframe so you can see it in action:
And you can click here to see how it’s done (just view the source):
If you like this flag, feel free to copy the source onto your own websites to display your own CSS-based American flag to wow your friends and impress the ladies (or gents, as you prefer). And for a nice extra touch, highlight the flag. You’ll find a hidden message along the right-hand side.
So how is it all done? Read on!
Building the American Flag out of XHTML and CSS
As always, we start with the XHTML. The basic structure is this:
<div id="flag"> <div class="blue"> ...stars go here... </div> ...stripes go here... </div>
Pretty basic, really. And the stars and stripes themselves are pretty darn easy, too:
<p>★★★★★★</p> <p>★★★★★</p> ...9 alternating rows of 6 and 5 characters...
Those funny characters in the paragraphs are ANSI character entities. It’s a way of calling on characters that exist in typefaces, but not on your keyboard. The character code above is for a five-pointed star. It should work in nearly every browser on nearly every computer, but I’ve noticed that some (but not all!) installations of Internet Explorer have problems finding the star. If you’d prefer, you could always just use asterisks instead.
<p class="red stripe">Your hidden message</p> <p class="white stripe">would go in here.</p> ...13 alternating rows of "red" and "white" classed paragraphs...
The stripes are equally simple. Each stripe is a paragraph with a “stripe” class and either a “red” or “white” class, depending on which you want it to be. You’ll need thirteen of them in all, starting and ending on red. And I know I’ve mentioned before that it’s bad practice to name classes according to what they look like instead of what they are, but since this is a purely visual exercise, I think we can let that slide. :)
So let’s move on to the CSS. We’ll start by defining the area around the flag contents:
#flag {
font-family: "Lucida Sans Regular", sans-serif;
width: 398px;
border: 1px solid #ddd;
margin: 0 auto;
position: relative; }
I’ve given the flag an overall width of 400 pixels (398 plus two 1 pixel borders on either side) so that it would fit nicely on most websites, but you could really make it any size you wanted. The margin is just centering the flag: you could remove it if you wanted, and everything would function just fine. The “position: relative” rule is important here, because it allows us to absolutely position elements within our relatively positioned box. And I’ve specified the font-family that I have because it’s one that I know has the star specified in its font file, and I’m hoping that will help Internet Explorer find it more easily. More modern browsers like Firefox and Safari, so far as I can see, tend to find the star character even without this help.
So now that we have an outline, let’s build the blue field and white stars:
.blue {
position: absolute;
top: 0;
left: 0;
width: auto !important;
width: 180px;
background-color: #00348c;
color: #fff;
text-align: center;
padding: 2px 0 5px 8px !important;
padding: 2px 0 5px 0; }
.blue p {
letter-spacing: 12px;
height: 14px;
font-size: 20px;
line-height: 14px;
margin: 0; }
To start, we’re absolutely positioning the area to the top-left corner of our flag. Next, we’re specifying two widths: a width of “auto” that most browsers read, and a specific width for Internet Explorer (which doesn’t understand the !important rule). Without these two rules, most browsers will work just fine, but in IE6 the blue field will take up the entire top 2/3 of our flag. Which, incidentally, creates a pretty cool flag… just not the American one. :)

Next up, we’re specifying a nice deep blue background color, and setting our font color to white. We’re also center aligning the text: this is what allows our alternating-sized rows to align just like the real US flag does. And we’re also applying some padding. Unfortunately, the padding looked a little wonky in IE6 (go figure), so I used the !important rule again to add a unique padding rule for that browser.
In the paragraphs containing the stars, we’ve specified a letter-spacing: this lets us get much more accurate spacing results than if we’d relied on regular spaces or non-breaking spaces ( ) between our stars. Then we specify a height, font-size, and line-height for each of the paragraphs. The height and font-size are the same, to center the star within the paragraph. The font-size is actually larger, however, which allows us to overlay our paragraphs slightly. The result is much more like the star pattern on the real American flag. I’m also setting the margin to zero, because otherwise the default paragraph margin would wreak havoc with our spacing.
Next up, let’s CSS-ify the stripes:
p.stripe {
height: 19px;
font-weight: bold;
text-align: right;
padding: 0 5px;
margin: 0; }
.red {
color: #f70029;
background-color: #f70029; }
.white {
color: #fff;
background-color: #fff; }
Each of the stripes in my example is 19 pixels tall. This is the result of some pretty irregular math that I won’t go into detail about: suffice it to say, the goal is to get the bottom of the blue field to line up with the bottom of the 9th stripe. I’m also applying a boldface, aligning the text to the right, and applying margins and padding. This is all for the “secret” hidden messages inside the stripes. If you’re not including a message in your flag, those rules aren’t necessary and can be trimmed.
After that, we’re styling the red and blue stripes. It’s a simple thing: we’re just setting both the foreground (text) and background colors to the same shade, so that the text is invisible until it’s highlighted.
And finally, I added a few special rules just for the highlighted text:
.red::-moz-selection {
color: #fff;
background-color: #f70029; }
.red::selection {
color: #fff;
background-color: #f70029; }
.white::-moz-selection {
color: #000;
background-color: #fff; }
.white::selection {
color: #000;
background-color: #fff; }
These are advanced selectors that don’t work on every browser, but I think it’s a nice effect for those that do (like Firefox and Safari). What we’re doing is modifying the color of the selected text from the browser defaults to new variables. On the red stripes, we’re setting the background color to the same red shade as the stripes themselves and turning the text white. On the white stripes, we’re going with a white highlight and black text. The result is that the viewer never actually sees the “highlighted” background color: they just see the text magically appear when they select the flag.
And voila! You’ve built an American flag out of XHTML and CSS. That should be good for at least one free beer at your friend’s barbeque this weekend. You can click here to see it in action again:
If you do use this anywhere, drop me a line in the comments. I’d love to see it in action!
Find Deprecated Elements with Diagnostic CSS Highlighting

I have to admit that I’m a bit of a code purist. In my heart of hearts, I’d really like to think that every developer out there that this site helps will turn around and produce clean, semantic XHTML to which to apply their lovely, efficient CSS. But that isn’t always the case. Sometimes people write code that isn’t quite semantic, whether they’re in a rush or just don’t know any better. Or sometimes designers are charged with redesigning a website that was first built during the Neolithic period.
Any way you slice it, there’s still a lot old-skool code floating around out there, and it can be a bear to dig through all that HTML to find the bits that could use a good refreshing. So once again, CSS comes to the rescue! The technique I’m talking about today is sometimes called “CSS Diagnostics.” Basically, you’re just using CSS to highlight specific elements and attributes – specifically, the ones that shouldn’t even be there in the first place.
Our first order of business is to decide what elements you’d like to weed out of your code. You could create a list of every single deprecated tag out there, but most developers didn’t use every tag out there. For our purposes, I’m going to look for the <font>, <center>, <s> (strikethrough), <u> (underline), <b> (bold), and <i> (italic) tags, which probably make up around 80% of the still-common deprecated tags out there. If I want to see where those tags are used in any website, all I need to do is apply some CSS to make them stand out:
font, center, s, u, b, i {
color: #000;
font-weight: bold;
background-color: #f99;
border: 3px solid #c00; }
And just like that, all of our deprecated tags are boldfaced on a light red background with a nice, wide dark red border. And assuming that wasn’t your previous design of choice (please tell me that wasn’t your previous design of choice), they should stand out on your website like the big, red sores that they are. :)
And that takes care of our tags, but what about all those deprecated attributes out there that might be applied to perfectly legitimate tags? For that, we’ll use the magic of CSS attribute selectors (more on those here). So for example, if I knew that the previous developer of the site I’d just inherited was fond of applying margins to their body tags using “rightmargin,” “leftmargin,” and so on, and also loved to scatter “bgcolor” and “background” attributes like so many apple seeds, I could just write a rule like this to weed them out:
body[bottommargin], body[leftmargin],
body[rightmargin], body[topmargin],
*[background], *[bgcolor] {
color: #000;
font-weight: bold;
background-color: #fc6;
border: 2px solid #c60; }
Here I’m using attribute selectors to highlight elements with particularly unsavory attributes. I’m also using the universal selector (*) to find all instances of attributes that can apply to multiple types of elements (like backgrounds). That way, I don’t have to write out every possible combination of element and attribute under the sun. And just like that, I’ll be able to hunt down all sorts of problem bits of code! You can see our examples from above in action here.
A few words of caution: when you’re doing this sort of styling, it’s important to apply these styles after all of your other CSS has been applied. That way, you don’t accidentally overwrite parts of your diagnostic CSS with other rules later on down the line. To do that, either put your diagnostic rules at the bottom of your CSS files, or create a whole new file for your diagnostic rules and <link> them after your main CSS file, or just copy and paste them into a <style> tag if you’re only diagnosing a page or two.
Also, as mentioned in the last article about attribute selectors, IE6 doesn’t recognize them. Of course, since this are purely diagnostic rules, that shouldn’t be much of a problem… just be sure to view your website in a modern browser (Firefox, Opera, Safari, IE7 (if you must), etc) when checking it for problems. And really, if you’re still using IE6 for all of your web design work, you’ve bigger issues to work through than just a deprecated tag or two here and there. :)
And finally, this build-your-own-diagnostic method is great if you know what to look for, but if you’d prefer a more one-size-fits-all solution to your diagnostic woes, I’d suggest downloading a full diagnostics stylesheet, like the one Neal Grosskopf offers here. However, be aware that his solution will highlight elements and attributes that are technically deprecated but still commonly used to good ends – such as the “height” and “width” attributes on images. I may be a code purist, but I still find those attributes mighty useful!
Fixing the IE6 Whitespace Bug

Sometimes, when I’m building a vertical navigation menu (like the one pictured above), Internet Explorer 6 will fight with me in a fairly annoying way: it adds a bunch of white space between the list items (specifically, I think it’s adding space below each list item). This space isn’t a margin, and it isn’t padding… it’s just empty, un-selectable space. So what’s going on, and how do we fix it?
The “what’s going on” part is simultaneously simple and perplexing: IE6 is treating all the empty space inside of your HTML lists – that is, the stuff between your closing </li> and next opening <li> tag — as real space. That’s the simple part. The confusing part is, why would it choose to interpret this space as “real,” when it ignores all of the other space between tags in pretty much every other situation out there? Well, that’s just IE6 for you, and that’s the perplexing bit.
Luckily, there is a really easy solution to this problem. Actually, truth be told, there are several solutions. Depending on your situation, each might be the right fix for you.
Fix #1: Remove All Whitespace
This is the most arcane of all the solutions, but to be honest, it’s the one I’ve used most often in the past – because I didn’t know about the other solutions! If you remove the white space from your code, this prevents IE from having anything to screw up. Specifically, if you remove the white space between your closing list item and the next opening list item, and your last closing list item and the end of your list, this will fix the problem. So you just need to turn this:
<ul> <li><a href="#">First Item</a></li> <li><a href="#">Second Item</a></li> <li><a href="#">Third One!</a></li> </ul>
Into this:
<ul> <li><a href="#">First Item</a></li><li> <a href="#">Second Item</a></li><li> <a href="#">Third One!</a></li></ul>
Like I said, this isn’t exactly an elegant solution. But it does work, and it can be useful in places when CSS isn’t entirely reliable (like in HTML emails).
Fix #2: Float the Anchor Tags
Jon Hicks popularized this fix years ago. Basically, you float the anchor tags left, and then clear them left as well, like so:
ul a {
display: block;
float: left;
clear: left; }
This causes your links to behave like floated elements, which naturally don’t have any space between them. Unfortunately, it also prevents your links from filling all the horizontal space available, which would make a mess of the example I used above, because I’m relying on that width to create a background color and a border. However, if your links don’t have any fancy hover states or borders, this solution would work just fine.
Fix #3: Apply a Bottom Border
Another useful solution is to apply a border to your list item. Why does this work? I have no idea. Does a border just anywhere work? Nope. It has to be applied to the bottom of the list item (or to all four sides, as long as the bottom is included):
ul li {
border-bottom: 1px solid #666; }
I suppose the logic on this one is that the space is on the bottom of the element, so specifying a definitive edge to the box causes IE6 to recognize the “real” end of the element. Whatever the reasoning, it works, and it’s a good solution if you don’t mind a pixel of extra space in between your elements in return for getting rid of the great swaths of space IE had introduced. And sometimes it even works in the design. In the image above, for example, the border between the items could just as easily be applied to the list item instead of the anchor (which is where I had placed it initially).
Fix #4: Use Display: Inline
In my experience, the most useful solution of the four is to force your list items to display inline, instead of as a block-level element (which they are by default):
ul li {
display: inline; }
As far as I can tell, this technique was first popularized by Andy Budd waaay back in 2003 (of course, he was dealing with IE5 back then). I like this solution because it seems to do the least harm to my lists. It doesn’t add any additional space that I need to account for. It also doesn’t harm the size of my anchor tags: if I apply a “display: block” to my anchors, like I’ve done in the image above, my anchor will stretch out the “inline” list item to its standard size.
Any of these solutions will remove the extra space from between list items in IE6. The key is simply to pick the fix that works best with your particular design.
Level the Playing Field with Reset Style Sheets

Scott Phillips is a web developer working at Drake University in Des Moines, Iowa.
The most frustrating part of learning cascading style sheets is getting consistent results across browsers. As you probably know, not every browser supports every rule in the same way (or at all).
Luckily, strategies have emerged that can help CSS newbies keep their sanity. The first is to write CSS so that it works in a browser that has solid support for CSS (like FireFox or Opera) and later tweak it, as needed, to work correctly in others (like IE6). Another strategy is to use a validator to find any simple syntax mistakes. These days, more and more developers are using a reset style sheet to cancel out pesky differences between browsers.
What’s the problem?
Even when you don’t use CSS in your web pages, you are still using CSS in your web pages. Huh? I’ll explain. Begin with the simplest page you can imagine:
<html> <h1>Here is my title.</h1> <p>Here is my paragraph.</p> </html>
View it with several browsers and you’ll see subtle differences. The margins are off. The font sizes and weights are different. We’ve hardly begun and already our pixel-perfect design is breaking down!
Here is what’s happening. Every browser has built-in default styles. To see Firefox’s on Windows XP, for example, open the file C:\Program Files\Mozilla Firefox\res\html.css. You’ll find rules like this:
h1 {
display: block;
font-size: 2em;
font-weight: bold;
margin: .67em 0;
}
...
blockquote[type=cite] {
display: block;
margin: 1em 0px;
padding-left: 1em;
border-left: solid;
border-color: blue;
border-width: thin;
}
...
hr {
display: block;
height: 2px;
border: 1px -moz-bg-inset;
margin: 0.5em auto 0.5em auto;
}
The lesson is this. If you don’t express an opinion about how an element should look, the browser will substitute its own. We’ve already seen that browsers never agree. Furthermore, even if an element looks identical across browsers, you can’t assume it is actually being treated identically (i.e. one browser may use a default margin for the white space around a list while another uses padding). Make a seemingly small adjustment and suddenly they both change in different ways. What a mess.
What can we do?
Zero-out the default browser styles. Then replace them with your own. A very simple reset rule looks like this:
* {
margin: 0;
padding: 0;
}
That cancels out margin and padding for all elements on the page. From here you might want to continue by resetting font sizes and removing image borders:
html {
font-size: 1em;
}
body {
font-size: 100%;
}
:link img, :visited img {
border: 0;
}
It would also be handy to fix inconsistencies with lists and tables:
table {
border-collapse:collapse;
border-spacing:0;
}
ol,ul {
list-style:none;
}
Slap all that code into a file called reset.css and @import it at the top of every page. You are on your way to more consistent results and fewer debugging headaches.
Standing on the Shoulders of Giants
Our reset style sheet is simple but effective but it’s just the beginning. The universal selector (*) can occasionally cause issues of its own. And inheritance problems can also crop up as you continue to expand your reset style sheet.
Luckily, web pros like to share. Yahoo has released their own reset style sheet for us to use, called Reset CSS, as a part of the larger Yahoo User Interface (YUI) library. Eric Meyer, a full-fledged CSS Jedi, has also done a lot of work on a robust reset style sheet. Both are excellent, and I recommend studying and adopting either (or parts of both) of them into your own projects.
Using Definition Lists: Question & Answer formatting

This guest article was written by Chris Coyier of CSS-Tricks, a site featuring tips, tricks, and tutorials on web design.
Unordered lists seem to get all the love these days, but there are just some things that are better semantically described with definition lists. Never heard of them? I’m not surprised. Here is the basic syntax:
<dl>
<dt>Definition Term</dt>
<dd>Definition Description</dt>
</dl>
There are two big differences between unordered lists and definition lists. One, there are two different elements that belong in a definition list: dt’s & dd’s. In unordered lists, all you have is li’s. Two, the only default styling applied to definition lists is a bit of a left-margin to the dd elements — no bullets or other strange positioning to fight.
Having two different tags to work with is what makes definition lists valuable. Take for example the need to create a FAQ’s page with a bunch of questions and their answers. Each question and answer group would really benefit from having a parent element, because then you could, for example, control the spacing between them or perhaps apply a border to visually separate them.
Many people would go straight for the div. With something like:
<div class="qa">
<h4>Question</h4>
<p>Answer</p>
</dl>
The problem with this is that div’s are very commonly used. Chances are, your page is already using several so it’s likely you will need to apply an unique class to the div to style it individually.
Other people will go straight for the unordered list:
<ul>
<li class="question">Question</li>
<li class="answer">Answer</li>
</ul>
The problem with this is that since you only get li elements in your ul, you will need to apply unique classes to them in order to get different styling.
I propose that the best elements to use for something like question/answer content is the definition list:
<dl>
<dt>Question</dt>
<dd>Answer</dt>
</dl>
Will using a div or an ul work? Sure, they’ll work just fine and nobody is going to slap your hand for using them. But if you want to be a super hip semantics junkie, you’ll use a definition list. You get all the advantages: a parent element for styling the whole group and different tags for the question and answer so they can be styled separately without needing to use unique classes. If needed, you can also use multiple dt’s and dd’s and use them in any order you wish.
Check out this example of a question and answer list using definition lists (click the image to see a live example):
Writing CSS Shorthand

Writing Cascading Style Sheets saves you time and bandwidth in the long run by removing all of the presentational elements and attributes from your web pages and moving them into a separate document. But sometimes that CSS document itself can get pretty long as well. So what do you do then?
There are lots of things you can do to help – embracing the cascading nature of CSS helps a great deal, as does combining CSS declarations using sequential selectors. But another trick that can really help cut down on the size of your CSS is to use CSS shorthand properties whenever possible. There are six shorthand properties for various areas of your CSS: margins, padding, borders, backgrounds, list-styles, and fonts. I’ll go through each of them below.
The margin shorthand property combines the margin-top, margin-right, margin-bottom, and margin-left properties into one single property. So instead of writing this:
div {
margin-top: 5px;
margin-right: 8px;
margin-bottom: 3px;
margin-left: 4px; }
You could shorten it all down to this:
div { margin: 5px 8px 3px 4px; }
It’s important to remember to always put your margins in the shorthand property in the following order: top, right, bottom, and left. Basically, just start at the top and work your way around the element clockwise. And if your top/bottom and left/right margins match, you can boil your shorthand down even further:
div { margin: 5px 8px; }
The rule above applies a 5 pixel margin to the top and bottom of your div, and an 8 pixel margin to the left and right sides. If all four of your margins match, you could even just write this:
div { margin: 5px; }
The padding shorthand property works exactly the same way as the margin shorthand. The biggest thing to remember about both of these properties is to start at the top and work your way around clockwise. And if you’re shortening it to two values, the top/bottom value always goes first, followed by the left/right value. Further, if you don’t need to specify a value on any one of the sides, you can just specify a zero (0) size with no unit of measurement.
div { padding: 30px 0; }
The border property allows you to combine the border-width, border-style, and border-color properties into one. The width comes first, followed by the style, and then the color. So instead of writing out all this:
div {
border-width: 3px;
border-style: solid;
border-color: #c00; }
You could boil it down to a single rule, like so:
div { border: 3px solid #c00; }
The background property is fairly powerful, in that it combines five rules into one: background-color, background-image, background-repeat, background-attachment, and background-position (in that order). So instead of writing this verbose mess of code:
div {
background-color: #fff;
background-image: url(../images/bg.gif);
background-repeat: repeat-y;
background-attachment: fixed;
background-position: top center; }
We could boil all of that down to this little snippet:
div { background: #fff url(../img/bg.gif) repeat-y fixed top; }
Also note that I skipped the “center” portion of my background-position property: if you specify one background position (i.e. “top”) but neglect to specify a second position value, “center” is the assumed value.
The list-style shorthand property isn’t used all that often, but it can save you a couple of lines of code. It combines the list-style-position property with either of the list-style-type or list-style-image properties – you could probably specify both, but list-style-image would overwrite the list-style-type property with whatever image you selected. So instead of writing this:
ul {
list-style-type: square;
list-style-position: inside; }
You could write this:
ul { list-style: square inside; }
Generally speaking, however, I tend to only use this shorthand when I’m looking to remove styling from the list (as when building a navigation bar):
ul { list-style: none; }
The font shorthand property is probably the most powerful of all the shorthand properties. It combines a grand total of six properties into one: font-style, font-variant, font-weight, font-size, line-height (even though it’s not technically a font property), and font-family. So instead of writing out all six of these rules:
p {
font-style: italic;
font-variant: small-caps;
font-weight: bold;
font-size: small;
line-height: 1.2em;
font-family: Helvetica, Arial, sans-serif; }
I can get by with a single declaration:
p { font: italic small-caps bold small/1.2em Helvetica, Arial, sans-serif; }
Of course, most of the time you won’t be specifying all six of those properties at once – I can’t even imagine how difficult it would be to read italicized, bold-faced small caps! But it is very useful for specifying your font-size, line-height, and font-family all in one place. That way, all of your typeface information sits one convenient location.
All About: CSS Positioning

At some point or another, if you want to lay out a complex CSS design, you’re probably going to have to turn to the veritable Swiss Army knife of advanced CSS layout: the position property. There are four possible values for this property: static, relative, absolute, and fixed. Let’s briefly go through each.
The static position value is sort of like the giant oversized flathead screwdriver in the Swiss Army knife: initially, it really doesn’t look like it does much at all. That’s because all objects are “static” positioned by default. Therefore, if you whip out a “static” position on an object that doesn’t have anything else applied, you can expect it to do… absolutely nothing. However, it can be useful if, for example, you’ve set a “relative” position on every image in your website, and then you need on specific image to behave normally. That’s when you suddenly realize that the giant flathead screwdriver is exactly the right size for replacing the screws on the bathroom vent cover. It has finally earned its keep.
Relative positioning in CSS is a bit like the pair of scissors in a Swiss Army knife: it has a pretty obvious function, but it doesn’t always work as well as you’d expect (or at least, it doesn’t the same way as you’d expect). Using the relative position value, in conjunction with the top, bottom, left, or right properties to move the object, moves an object from its initial location in the document flow to a new one. However, the old space where the object used to live is left open. Therefore, if you have three paragraphs, and position the third paragraph like so:
p#two {
position: relative;
top: 2em;
right: 3em; }
Then you’d end up with a document that looked something like this (I’ve added some styling to the paragraphs to make the positioning easier to see). As you can see, the paragraph as moved down and left (or more accurately, away from the top and right) from where it was originally, but the space reserved for the paragraph has remained intact. This can be useful, as long as you understand what you’re getting when you relatively position. It’s like understanding that the scissors in your knife are okay at cutting fabric in an emergency, but they’re never going to replace your kitchen shears.
Absolute positioning is the knife of the Swiss Army knife: it’s what everyone generally thinks of (and expects) when they think of positioning elements. Absolute positioning an element pulls it completely out of the document’s flow – the space it would have otherwise occupied is closed up, and the element is placed wherever you’d like it to be placed (according to the top/right/bottom/left properties). So this little bit of code:
p#two {
position: absolute;
bottom: 2px; }
Will result in something like this. Note a few things about this example: first, since we set the “bottom” property the element is positioned according to the bottom of the browser window (and
And last but certainly not least is the fixed position property. It’s a little like that slightly sharp, oddly curved piece of metal in your Swiss Army knife – you’re not quite sure what to do with it at first, but once you realize it’s perfect for popping the top off a beer bottle, it quickly becomes your favorite tool in the arsenal. Fixed positioning behaves a little like absolute: it pulls the element out of the document flow and closes the original space behind it. However, unlike absolute positioning, once you’ve specified a spot for the element, it stays there… even if the page behind it moves. So take this code:
p#two {
position: fixed;
top: 10em;
width: 35em;
background-color: #fcc; }
That will produce a document that behaves like this. No matter how much you scroll, that paragraph will stay in the exact same spot. This can be really useful if you need something to always stay in one spot, like an important navigation bar at the top of the page, or footer information that you always want to be visible at the bottom of the window.
Once you learn to master these properties, advanced CSS layouts start to become a whole heck of a lot less mysterious. If you’d like to learn more, be sure to subscribe to the CSSnewbie RSS feed, because later this week I’ll be talking more about how to use these properties in useful and interesting ways.
Use Comments to Organize Your CSS Design

It’s inevitable: the longer you work with CSS, the longer your CSS files will grow. And the longer your files get, the tougher it will be to find what you’re looking for when you go back to edit your website’s styles later on down the road. This is where CSS comments can really come in handy.
The syntax is amazingly simple: You start a CSS comment with /* and end them with */ – like so:
/* This is a CSS Comment. */
body {
font-size: 80%;
}
A single CSS comment can also span multiple lines, like this:
/* This CSS was written by Rob.
He thinks of it as his own child, so
you'd be best off asking permission
to use it. ;)
*/
body {
font-size: 80%;
}
So what are CSS comments good for? Well, in addition to identifying the creator of a CSS file (as shown above), you can also use your comments to keep your CSS more organized. For example, I use comments to organize my CSS into sections, like this:
/* Top navigational elements. */
ul#topnav {
property: value;
}
/* Main content area. */
#content {
property: value;
}
This makes it much easier to come back though and add or remove values from a stylesheet later on.
I also use comments to identify any “hacking” I’ve been forced to do.
.column {
height: 1%; /* Makes IE behave itself. */
}
That way, if the hack ever becomes unnecessary or causes a different problem down the line, it’s that much easier to find it.
What else do you use CSS comments for?
The 4 CSS Rules of Multiplicity

One quick and easy way to keep your CSS clean and well-structured is to remember (what I’m going to title) the four CSS Rules of Multiplicity. They are:
- Multiple declarations can live in a single rule.
- Multiple selectors can preface the same rule set.
- Multiple rules can be applied to the same selector.
- Multiple classes can be set on a single element.
Multiple declarations in a single rule is the most fundamental of the four CSS Rules of Multiplicity. Simply stated, it means you can have as many CSS declarations as you want between your opening and closing braces, like so:
body {
property-1: value;
property-2: value;
...
property-infinity: value;
}
Multiple selectors can really help keep your CSS clean by grouping your rules together. Consider the following example:
p {
font-size: 110%;
color: #333;
}
ul {
font-size: 110%;
color: #333;
}
When rules are identical like this, you can combine them by using sequential selectors, like so:
p, ul {
font-size: 110%;
color: #333;
}
But what happens when you have two selectors that have very similar, but not quite identical, properties? That’s when multiple rules come into play. Here’s an example:
p {
font-size: 110%;
color: #333;
}
ul {
font-size: 110%;
color: #333;
font-weight: bold;
}
The paragraph and unordered list share a few properties in common, but not all. But you’re allowed to refer to the unordered list more than once, so you could write something like this:
p, ul {
font-size: 110%;
color: #333;
}
ul {
font-weight: bold;
}
Another way to tackle having multiple rules in common across elements is to create multiple classes. For example, you could create a rule like this:
.container {
padding: 5px;
border: 2px solid #ccc;
background-color: #f2f2f2;
}
But then a while later, you decide you want something that is almost the same as your container class, but the text within is larger and boldfaced. You might be tempted to write a completely new class that includes the padding, border, background, and font size and weight that you need. But instead, you could just create a second class containing just the differences between the two, like this:
.strong {
font-size: 150%;
font-weight: bold;
}
And then apply both classes to your XHTML element thusly:
<div class="container strong"> This text is in our container, but is also big and bold. </div>
By using all four of these examples of multiplicity together, you can keep your CSS looking lean and clean. And luckily, unlike the movie version of Multiplicity, Michael Keaton doesn’t get dumber the more often you use them.
When to Use Inline, In-Document, and Linked CSS

There are three ways to inject a bit of CSS magic into your web pages. They are inline styles, in-document styles via the <style> tag, and linked style sheets. Each is valuable in its own right – the trick is knowing when to use them.
Inline styles are the most basic way of applying styles to an element, in that you apply the styles directly to the tag in your HTML. For example, this is an inline style:
<p style="font-size: 200%;"> This text will be twice the size of your other paragraphs. </p>
This is most useful when you are trying out new tags. In the example above, if I had several paragraphs on my page, I could easily try out several styles on several paragraphs to more quickly find the exact look I was going for. It’s also useful if you need to override a more global style in one specific instance: if you’re using inline, in-document and linked CSS all at the same time, inline styles take precedence.
In-document styles make use of the <style> tag within the HTML document’s head, like so:
<style>
p {
font-size: 200%;
}
</style>
This technique is best used when you have one page that needs to be styled differently from every other in your website. You still have the flexibility to apply styles to your entire document, and those styles have the opportunity to cascade and change broad swaths of your page with little effort, but to apply these styles to more than one page, you have two options: copy and paste the styles into all your documents (messy, if you ever make any changes), or use linked style sheets.
Linked style sheets are the preferred method for applying CSS to a website. Here, your CSS resides in a separate document, outside of your HTML entirely. You then link to it in your document’s head like this:
<link rel="stylesheet" href="style.css" media="screen" />
There are three important pieces here:
- Rel: Stands for “relationship.” Tells your browser that this is a stylesheet.
- Href: Stands for “hypertext reference.” This is how your browser knows where to find the stylesheet. If it’s in a different directory, you’ll have to show that in your href.
- Media (optional): Says that this stylesheet should be applied to the screen. If you leave this off, it will still be applied to the screen.
And most importantly, you can just include this one line of code in the top of every page you want to have styled (between the <head> and </head> tags), and the browser takes care of the rest. Now if you ever make a change to your CSS, you can just change it in that one file, and the changes will take place automatically across your entire site. And that, when you get right down to it, is really what makes this whole CSS thing so great in the first place.














![Click here for more information. [your ad here] Become a Sponsor! Click here to learn more.](/img/your-ad-here.gif)