Simple CSS Tips

It wasn't that long ago that the de-facto way to layout web pages was to use tables.  You ended up with these heinously nested tables that made it very difficult to find anything in your code and were not very flexible.  Then came the advent of CSS.  It opened up a lot of possibilities, but it could be abused, or misused just as easily as tables -- you still see a lot of very poorly written CSS that is worse to maintain that tables.

All that to say, it took me a while to feel really comfortable with CSS, but here are a few tips and tricks I've picked up along the way to make your CSS clean and reusable.

Tip 1 margin: 0 auto;

One of the most confusing things to me when I started using CSS was trying to figure out how to align something centered on the page.  The trick is to create a div, set the width you want and set the margin to 0 auto.  The first 0 tells the div to have no top or bottom margin and the auto tells the left and right margins to have equal margin, aligning the div in the center of the page.

    margin: 0 auto;

Tip 2 Multiple Classes

You can assign multiple classes to your html elements.  For example, You might have a class called "product" that set a particular font size and color for a product on your website.  You could keep the product class on your div and add to it a "featured" class that might highlight the product using a background color.  The beauty of CSS is that you can apply both classes and not have to replicate the product attributes in the featured class. You separate multiple classes with a space in your HTML.  Here is an example below:

<div class="product featured">
    The best thing your feet have ever walked in!

.product {
    width: 150px;
    height: 150px;
    font-family: Arial;

.product h3 {
    font-family: Tahoma, Verdana;

.product.featured { /* This applies to elements with product and featured applied. */
    background-color: Red;

Tip 3 Absolute Positioning

Absolute positioning can be abused, but it is very helpful sometimes.  When you want to stick something somewhere and don't want it's positioning affected by other things on the page, absolute positioning is the way to go.  A lot of times I'll have a header div and I want the menu to sit at the bottom right of the header.  You could float the menu right and add top margin until it was positioning at the bottom of the header, but what if you change the height of the header, you then have to adjust your margin.  Here is some html and css I typically use for this type of setup (simplified):

<div id="header">
    <ul id="menu">
        <li><a href="Home.aspx">Home</a></li>
        <li><a href="About.aspx">About us</a><li>
        <li><a href="Contact.aspx">Contact Us</a></li>

#header {
    background-color: Blue;
    position: relative; /* Important so our menu is positioned relative to the header */

#menu {
    bottom: 5px;
    right: 10px;
    list-style: none;

#menu li {


Post a Comment