Archive from Mar 2008
Harnessing CSS Positioning: Part 2

We’re continuing our look at CSS positioning in this article. If you missed last week’s article on the subject, you might want to start there. Today’s article will take a look at two more ways in which absolute and relative positioning can really come in handy: absolute positioning ads and messages to ensure they’re not missed, and creating attractive fractions in your text with CSS and some semantically meaningful XHTML.
Absolute Positioning Ads and Messages
There may be times when you really, really need your website patrons to notice a certain bit of information. Perhaps you’ve added a new section to the site and want to draw attention to it. Maybe you’re moving your entire site to a new domain and want to give your readers a heads-up. Or maybe you’ve just released a new product and want to ensure it gets the attention it deserves. In these cases, absolutely positioning the information can really make it stand out.
The first thing you need to do is decide what you want your container to be: if you want to position your element according to the edges of the body tag, then you don’t need to do anything. If you want to position your message according to some other element (like a containing div), be sure to refer to last week’s tip on positioning inside of other elements.
Then, all you need to do is style your element and absolutely position it on the page. Something like this would do the trick:
.message {
/* Positioning the message box. */
position: absolute;
top: 0;
left: 0;
/* Styling the message. */
text-align: center;
width: 100%;
border-bottom: 1px solid #c00;
background-color: #faa;
font-weight: bold;
z-index: 10; }
And these styles would result in a difficult-to-miss message box that looks a little something like this. Or, for a real-world example, check out this absolutely-positioned advertisement on Woodsmith magazine’s homepage:
Classier Fractions with Relative Positioning
Every once in a while, you’ll come across a situation in which fractions could really come in handy (such as styling a recipe). If you already create a lot of documents with fractions, you’ve probably noticed by now that while it’s very easy to create attractive fractions in XHTML using the ¼, ½, and ¾ character entities (creating ¼, ½, and ¾, respectively), anything else comes out looking sub-par. There just isn’t a special character code to properly style nine-sixteenths. However, there is an easy way to do it with XHTML and CSS.
We’ll start with some XHTML that looks like this:
<p>Once planed, the board should be <span class="frac"><sup>9</sup>/<sub>16</sub></span>" thick.</p>
Already, just by using the <sub> (superscript) and <sub> (subscript) tags, we’re getting a lot closer to a realistic fraction. But let’s use CSS to get us a whole lot closer. With the markup given above, we have three selector “hooks”: the class on the span, the sup tag, and the sub tag. So let’s style all three:
.frac {
font-style: italic; }
.frac sup, .frac sub {
font-style: normal;
font-size: 65%;
position: relative; }
.frac sup {
top: 0.1em;
left: 0.05em;
vertical-align: text-top; }
.frac sub {
top: 0.1em;
left: -.1em;
vertical-align: text-bottom; }
We start out by italicizing our fraction: this makes the forward slash between our numerator and denominator even more pronounced. Then, we reset the font-style on our sub and sub tags (because they’re not italicized), make them a little smaller than normal, and give them a relative position. Finally, we position our superscript and subscript tags – bringing each slightly closer to the forward slash. We also ensure we’re measuring from the top of the superscript, and the bottom of the subscript, just to regularize any positioning problems.
The result, as you can see here, are fractions that are virtually indistinguishable from those created using XHTML entities. This means you could easily use both types of fractions in a single document and your readers would likely be none the wiser.
Thus concludes our look at the power and versatility of CSS positioning. Of course, these are only a few examples – there are countless other things you could accomplish with positioning and a bit of ingenuity. And if you have a favorite “position” or two that I haven’t mentioned, be sure to share them in the comments!
Great Resources Elsewhere: March 21 to March 28
Hackszine.com: Easiest cross-browser CSS min-height
The Amazing LI: Using CSS and Unordered List Items to Do Just About Anything
960 Grid System
Harnessing CSS Positioning: Part 1

Earlier this week, I explained the basics of CSS positioning: what it is and what your options are. Now I’d like to take some time and explain a couple of tricks for using positioning in the real world… stuff that really harnesses the true power of CSS positioning.
Absolute Positioning Inside Relative Positioning
One of the coolest and simplest ways to harness the power of positioning is to use a combination of relative and absolute positioning. Specifically, to absolute position an object inside of a relatively positioned object. Why is this so cool? Because of one of the under-understood rules of positioning.
Any time an element is absolutely positioned, it’s actually being positioned according to the boundaries of its containing block. By default, with no other objects positioned on the page, the containing block is the <body> tag. However, if you position any element further down in the hierarchy (like a containing div, for example), that positioned element becomes your new containing block. What’s that mean in practice? It means you can have some XTHML that looks like this:
<div id="wrap"> <p>This stuff is in the wrapper</p> <div id="sidebar"> <p>Sidebar information is cool</p> </div> </div>
Then, you can size and relatively position your wrapper div, like so:
#wrap {
width: 500px;
margin: 0 auto;
position: relative;
}
Here, all we’re doing is giving it a width, centering it with an auto margin trick, and then setting a relative position. But we’re not actually moving the div anywhere! Setting a relative position, but then not setting a top, bottom, left or right property means the element doesn’t move anywhere. But, because it has a “position” set, it becomes our new containing block. Now, we can specify styles on our sidebar that look something like this:
#sidebar {
position: absolute;
top: 0;
right: 0;
}
As we learned last week, setting our top and right properties to zero, with an absolute position, should move our sidebar to the top-right of the page. However, because our wrapper div became our new containing block through use of the relative position, the sidebar is actually just moved to the top-right corner of the wrapper div. This can be extremely useful when you have a fixed-width and centered web page: you may want to absolutely position elements according to your “page,” but not according to the browser window. This is how that’s done. You can see a slightly more involved example here.
Fixed-Position Navigation
If you have a website that tends to be a bit on the wordy/lengthy side (like, erm… this one?), it could be useful to ensure that the site’s navigation is always at the top of the page, no matter how far down your users scroll. For that, fixed positioning can really come in handy.
For this trick, all you need to do is develop a navigation bar of some sort (covered in more detail here), and then “fix” it to the top of your website. You’d start out with some XHTML like this:
<div id="wrap"> <ul id="nav"> <li>Home</li> <li>Contact</> <li>Etc</li> </ul> <h1>Page Title</h1> <p>This page is cooler than it looks.</p> </div>
Next, you’d want to pull your “fix” your navbar to the top of the page:
#nav {
position: fixed;
top: 0;
}
And really, that’s the meat of your code. The fixed position tells the browser to pull the navbar out of the normal document flow, and then affix it to the top of the page. Of course, because it has been taken out of your document flow, the navbar might be overlapping your text, which will move up the page to fill the space that the navbar has vacated. To ensure that doesn’t happen, you’d want to add some space to the top of your website. Something like this would do the trick:
#wrap {
/* Your padding should be the height
of your navigation bar, plus the
space you want between the navbar
and the top of your page. */
padding-top: 50px;
}
As the comment above states, you’ll want to add enough padding to compensate for the height of your navbar, as well as any extra spacing you want between your navbar and the content below. So if your navbar were 30 pixels tall, and you wanted 20 pixels of space before you got to your header, you’d want 30 + 20 = 50 pixels of space at the top.
And voila! You now have a navigation bar perma-fixed to the top of your browser window. No matter how far down your page your users scroll, your navigation will never be more than a few pixels away. You can see it in action here.
These are just two ways in which the position property can really make your life easier, your websites cooler, and your wife more satisfied. Stay tuned, because next week I’ll show you a couple of other neat positioning tricks: one for creating big visual impact with absolute positioning, and another for making subtle (but useful!) text changes using relative positioning.
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.
Write for CSSnewbie!

If you’d like the opportunity to write for one of the newest and fastest-growing CSS-centric websites out there, have I got some great news for you! CSSnewbie is looking for guest authors.
Here’s the deal: I’m going to be on vacation for a couple of weeks in mid-April. Rather than let my beloved website languish and stagnate, or furiously pump out a series of hastily written and subsequently sub-par articles in advance, I’ve decided to instead opt for guest authors.
If you have a great idea for a CSS-related article, email me with a brief explanation of your idea. I’ll take a look and let you know as soon as possible whether I think the idea would work on CSSnewbie. Don’t worry if the article isn’t anything like something I’ve written before – I’m very interested in trying new things and branching out a bit.
If your article is accepted, you’ll also get to put together a short bio that will be placed at the top of your article. This will give people the opportunity to learn more about you and to check out your work elsewhere. It’s a win-win situation: you get increased exposure for your own name and work, and I get to visit Europe without worrying about the health of my poor website stateside.
So once again, contact me with ideas as soon as possible – I’d love to work something out!
Great Resources Elsewhere: March 07 to March 14
woork: Write a well structured CSS file without becoming crazy
10 CSS Form Examples | Design Shack
The Evolution of Websites: How 10 Popular Websites Have (And Have Not) Changed
Using the CSS @import Rule

Even the most complex style sheet starts out with a single rule. But when you’re working on a particularly massive and complex website, over time your style sheet will inevitably start to reflect the site’s size and complexity. And even if you employ every trick of organizing your CSS in the book, you might find that the sheer size of the file is simply overwhelming. At that point, you might want to consider splitting your style sheet up into several smaller CSS files. That’s when the @import rule can come in quite handy.
The @import rule is another way of loading a CSS file. You can use it in two ways. One, within the header of your document, like so:
<style>
@import url('/css/styles.css');
</style>
But the following meethod is more useful for keeping your XHTML small and your code clean. You can import a style sheet from within another stylesheet. And better still, you can import any number of styles this way. So your document’s head could look like this:
<link rel="stylesheet" type="text/css" href="/css/styles.css" />
But then your “style.css” document could simply contain calls to all of your other style sheets:
@import url('/css/typography.css');
@import url('/css/layout.css');
@import url('/css/color.css');
/* All three CSS files above will be loaded from
this single document. */
This way, you can break up your gargantuan stylesheet into two or more logical portions — I chose typography, layout and color for this example, but you might prefer dividing your CSS according to the columns they create or something similar. Either way, the benefit is immense – you can have the same number of CSS rules overall, but in smaller, easier to manage units.
You can even load both your screen and print (or handheld, etc) stylesheets all at the same time using this trick. If you’d like to specify a media, just write your rules like this:
@import url('/css/header.css') screen;
@import url('/css/content.css') screen;
@import url('/css/sidebar.css') screen;
@import url('/css/print.css') print;
Like most cool things in CSS, this one comes with a couple of caveats:
- The @import rule isn’t recognized by the really old browsers out there… Netscape Navigator 4 skips over @imports entirely, and Internet Explorer 4 ignores them if you don’t use the (entirely optional, but generally used) parentheses. Of course, not too many people these days use either of these archaic browsers. And this problem can actually be useful if you’d like to hide some or all of your CSS from the browsers that can’t really support it.
- Your @imports must come before all other content in your CSS. And I mean all of your content. Even putting comments before the @import tag will cause your imports to fail. So be sure to do your imports before you do anything else.
- Internet Explorer (you knew it’d come up eventually) doesn’t deal well with specifying media types – it chokes. Basically, IE (versions 4-7) try to read the media type like it were part of the file name, causing the whole thing to come crashing down. As such, if you don’t want your CSS to have a default media type of “all,” you’re probably better off using a combination of the <link> tag and imports – specifying a media type in your link, and then importing the appropriate CSS within the file you’re linking to. I haven’t yet heard if IE8 suffers from this same problem (if you happen to know, please enlighten me in the comments!).
But even with those caveats in mind, this can be a really useful technique. No matter how big your website ends up getting, you’ll be able to keep your style sheets under control.
When to Use Margins and Padding

There are two ways in CSS to create space around your elements: margins and padding. In most usage scenarios, they are functionally identical – for example, if you add 20 pixels of either margin or padding to the left side of an element, that element will generally move 20 pixels to the right on the screen. But in truth, they do behave in slightly different ways. So when should you use margins, and when would padding be more appropriate?
Use margins when:
- You want your spacing to appear outside of the “box” created by a border property. Margins lie outside of borders, so you’d use them if you want your border to stay in one place. This can be useful if you have, for example, a sidebar with a border that you want to move away from your main content area.
- You don’t want your background color or image to invade your personal space. Background colors and images stop at the border, so if you’d rather keep your backgrounds out of the space you’re making, margins are the property you want.
- You’d like collapsible space on the top and bottom of your element. Top and bottom margins behave differently than side margins in that if two margins are atop one another, they collapse to the size of the largest margin set. For example, if I set paragraph to have a top margin of 20 pixels and a bottom margin of 15 pixels, I’ll only have 20 pixels of space total between paragraphs (the two margins collapse into one another, and the largest wins out).
Padding, on the other hand, behaves very differently in these scenarios. Thus, you’d want to use padding when:
- You want all of the space you’re creating to be inside your border. Padding is contained within your borders, so it’s useful for pushing your borders away from the content inside of your element.
- You need your background color/image to continue on into the space you’re creating. Your background will continue on behind your padding, so only use it if you want your background to peek out.
- You want your top and bottom space to behave more rigidly. For example, if you set the paragraphs in your document to have a top padding of 20 pixels and a bottom padding of 15 pixels, then any time you had two paragraphs in a row, they’d actually have a total of 35 pixels of space between them.
So as you can see, there are important differences between margins and padding that you should take into consideration when choosing which to use to move elements around the page. However, in those cases where either margins or padding could be used to the same effect, a lot of the decision comes down to personal preference.
For example, I tend to use margins almost exclusively when I’m trying to create space between two elements. In my mind, margins are used for creating space between elements, while padding is used for creating space within elements. Therefore, I use margins to move disparate elements apart, and padding to create a little breathing room within the elements themselves.
However, a case could also be made for using padding for effecting space between elements. From time to time, Internet Explorer 6 will have trouble with margins – there’s something out there known as the doubled-margin float bug that can wreak all sorts of havoc with pages laid out with margins when they’re loaded in our favorite “special” browser. Using padding almost exclusively does create a way around this problem. I personally tend to just use a CSS hack or two to make IE behave itself when we’re in public, but as I said, this can be an effective argument for ubiquitous padding.
Great Resources Elsewhere: March 07 to March 14
Smart Image Resizer — Shifting Pixel
8 Premium One Line Css Tips | Css Globe
Why Doesn’t My CSS Work? Five Quick Fixes.

Imagine: You’ve been working on your brand new, beautifully cascading style sheet for most of the day. You save your work, load it into a browser, and… what the heck?! Nothing’s working right! You know you didn’t make any huge errors in your code, but something is obviously wrong.
We’ve all been there before. But instead of wasting endless hours debugging your code, here are a few very simple things you can check in your CSS before you start pulling out your hair.
Closing brackets are notoriously easy to miss, especially if you don’t put them on a line all by themselves (and I usually don’t). Missing a single closing bracket can throw off your entire website, because the browser quits loading your rules as soon as it encounters the malformed code.
.sidebar {
width: 200px;
background-color: #333;
.sidebar h3 {
/* None of these rules are applied! */
font-size: 1.4em;
color: #fff; }
A missing semicolon can likewise cause your code to start behaving wonky. CSS specifications state that you don’t need a semicolon on your very last rule before your closing bracket, but in my experience that’s a great way to set yourself up for some heartbreak. As soon as you decide to add one more rule to that property, that missing semicolon is going to rear its ugly head.
.sidebar {
width: 200px;
background-color: #333
/* The following rule won't render! */
padding: 5px;
}
Is there any chance you have a misspelled class or ID? It may sound obvious, but I’ve spent far too much of my life trying to debug my CSS just because I misspelled something along the line. This, if anything, is a good reason to stick to whole words (or at least common abbreviations) when writing your CSS classes and IDs – it’s going to be easier to notice a misspelling in the “leftSidebar” class than it is the “ltSdbr” class.
.siedbar {
/* Dunno what a siedbar is, but I'm
pretty sure it's not in my XHTML. */
width: 200px;
}
Misspelled properties or values have also caused me more than their fair share of trouble. There are certain words I tend to misspell when I’m typing too quickly, and it just so happens that there are a lot of CSS properties with related names. I don’t care how much I’m “in the zone,” there’s still about a 50% chance I’m going to try to apply a “bakcground-color” somewhere along the line.
.sidebar {
/* The following property does exactly
bupkis. Dyslexics Untie! */
bakcground-color: #333;
}
Bad CSS values can be a bear to hunt down, particularly if you’re convinced that the value you’re using really exists. Some invalid values are more obvious than others – a background-color of “1px” would be relatively easy to spot, but what about a vertical-align of “center,” like I mentioned last week? We tend to think of things as being either aligned to the top, center, or bottom of a space… but CSS classifies that second option as the “middle,” not the center. An alignment of center won’t create nearly the presentation you’re expecting.
.sidebar img {
/* This image isn't really going anywhere. */
vertical-align: center;
}
If you start your CSS debugging by looking at these five common problem areas first, there’s a good chance you’ll save yourself a whole lot of time – and a massive headache to boot. If you have any other ideas for common areas of CSS misstep, offer them up in the comments!













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