Now Reading
CSS tips and tricks

CSS tips and tricks

code

Welcome visitors from Digg. The Blog Herald is one of the largest sites covering the blogosphere – and has been so for more than four years.

You can subscribe to our feed and visit our archives for more stories.

I’ve been writing CSS for about 2 years now and I still feel like every time I open up a blank file and begin writing CSS for a new design I learn something new.

For those of you that are new to CSS or experts always looking for a new trick, here are some of things I do on a regular basis to keep my code organized (kind of).

1. Size text without using pixels

If you’re wondering how some designers get font sizes to work using em as a unit rather than px, it’s easy. There is a trick that was written about a while ago (maybe on ALA) that resets the font sizes for the entire site so that 1.0em is the same as 10px.

body { font-size: 62.5% }

Simply throw the font-size: 62.5% bit into your body styling and you’re done. Now you can use ems to sizes your fonts rather than pixels.

So your paragraph styles might look something like this:

p { font-size: 1.2em; line-height: 1.5em; }

You might be wondering why it matters how you size fonts? Bulletproof design. Any major site needs to be able to withstand a user enlarging text (old people use the web too!), and setting absolute sizes is not good practice.

2. Make your code easy to read

When I was looking at some of the CSS coded by Rundle I noticed that he separated his heading tags nicely. It looked something like this:

h1 {}
h1#logo { font-size: 2em; color: #000; }
h2 {}
h2.title { font-size: 1.8em; font-weight: normal; }

Quickly scanning the CSS for the different heading tags is a breeze if you use this technique. It is also helpful if you’re sharing code or working on a large site where you are using the same heading tags (say, h2) in multiple places since you’ll be able to style each one independently and not worry about child classes inheriting attributes from the parent class.

I also use similar techniques for paragraph tags, anchor tags, and any other tag that requires multiple classes to look correct in every instance.

3. Separate code into blocks

This might be common sense to some of you but sometimes I look at CSS and it’s not broken down into “sections.” It’s easy to do an it makes working with code weeks, months, or years later much easier. You’ll have an easier time finding classes and elements that you need to change.

This is how I usuall break down my site:

/* Structure */

This is where I’d put the primary site structure divs and classes.

/* Typography */

This is where I would list things like paragraphs, headings, and other miscellaneous font styles such as small and strong tags.

/* Links */

This one is simple – all the styling for anchor tags.

See Also
wordpress developer salary

/* Lists, images, etc. */

This is where I would style images, lists, and any other elements that didn’t fit into the rest of the section. If I have an unordered list for the navigation I might setup a new section for navigation and setup all the styles for the navigation, including the list and link styles, in this section – it makes editing the navigation much easier.

4. Stop using so many divs!

This has been echoed by a lot of coders and standards nuts, and while I don’t think there is anything wrong with using a lot of block level elements, I laugh a little when I see someone style their article headlines using a div rather than a heading tag. Some people even style their bylines using a div! Try using the small tag or the a span for goodness sake.

5. Style everything at once

I noticed that I was typing “margin: 0; padding: 0;” in just about every element. I remembered seeing someone use “*” to style everything on a page at once. I decided it didn’t make much sense to define margin and padding over and over when I always gave them the same parameters.

It’s easy to do:

* { margin: 0; padding: 0; }

Now you only have to define margin and padding on elements where you actually want some.

Know of any other tips or tricks? Let me know :)

In this moving age of internet many internet providers have also come into the field of web hosting. Some of these companies are working as domain reseller while others are offering complete hosting services along with the basic internet marketing program. Most of these companies offer free wireless internet connection along with their hosting packages. Some internet phone service providers are also offering ppc search engines to their clients. Along with basic hosting and SEO services some of these companies also offer the services of online training. Above all webmasters should not go after the freebies init as these are not considered as recommended servers by most of the experienced webmasters.

View Comments (147)
  • Nice post Ben. I’ve fixed way too many CSS files that look like shit and takes time just to understand since everything is everywhere. Structure is necessary, even if it’s just for yourself.

    Styling everthing is a good tip that I’ll take from this post. Haven’t done it before but it sure makes sence. :)

  • The universal selector, while convenient, messes with form elements in Gecko browsers. It’s also overkill, since it applies to every single element in a document, whether or not it needs its margins/padding cancelled, if they even apply, slowing the browser down.

  • Big Roy – Glad you could get something out of it :)

    Su – How much does a padding/margin declaration slow down the server? Even on a major site that is styled primarily with CSS it seems trivial to think that the universal selector giving all elements a margin/padding of 0 would slow down the server too much.

  • Hey Ben, it’d probably be good to talk about just why 62.5% font-size declaration makes sizes easier to deal with.

    The default size of text in browsers is 16px and 62.5% of 16px is 10px. By bringing the default size down to a managable whole number like 10 (instead of 16) you can now easily do font-sizes in em units without busting out your calculator. 15px is 1.5em, 12px is 1.2em and so on. Without dropping the default size to 10px (62.5% of default) to start you’d be stuck doing multiples of 16 which isn’t fun.

  • Good tip, Mike on explaining the 62.5% thing in a clear way for us css-dolts.

    Seems like a smart way to manage text size in many sections.

    Ben – #5 “styling” is a good tip. Thanks

  • Ben – I think Su is talking about the speed of the browser as it renders the page on the client side. Once the response has been generated on the server and sent to the client it doesn’t matter how fast the server is. The site visitor’s own computer still needs to read the CSS rules and correctly postion, pad, margin, etc every single element on the page. The more rules and styles to apply the (potentially) longer the brower will take to finish loading.

  • Kinda good tips, but if you will I have a few caveats to add to them (which I’ve picked up in my 5+ years of css):

    1) While non-pixel based font sizing is definitely the way to write your css, there is one (IE) caveat. If you set the font-size of the body below 100%, IE has a problem with text-zooming. The work-around is to set your body to 100% explicitly and 62,5% on your div-container (or similar div).

    3) Yep. I noticed that Douglass Bowman puts an extra line of ==== underneath the section title, tit really improves legibility. So you’d get:
    /* Structure
    ======== */

    4) Absobloodylutely!

    5) You *can* but watch out: Everything really does mean everything. This means that you have to explicitly set padding&margin for everything, as you can’t depend on browser defaults anymore. I have found this to be more hassle than it’s worth.
    A better alternative would be to simply list the block elements you want pad&marginless like so:
    div, form, etc {pad:marg:}
    There are ready-made stylesheets which do this for you, ready to be included. (But as I don’t use them, I don’t have any links to them unfortunately)

  • I love seeing tips like this! I just want to add a few suggestions to #3 (section titles):

    – Please don’t define the same tag/class/id/etc. multiple tmes under different sections. If you’re very familiar with the CSS file in question, it’s probably really useful. But if someone else is trying to update a file you’ve written, it can become extraordinarily confusing when you think you’ve “found” the style definition you want to edit, and not realize you’re not seeing the whole definition. This cost me about two hours of work just last night, as I was working on a new blog template based off of an existing one.

    – Include a “Table of Contents” area in comments at the top to give someone new to the file an idea of how the styles are grouped

  • The default size of text in browsers is 16px and 62.5% of 16px is 10px. By bringing the default size down to a managable whole number like 10 (instead of 16) you can now easily do font-sizes in em units without busting out your calculator. 15px is 1.5em, 12px is 1.2em and so on. Without dropping the default size to 10px (62.5% of default) to start you’d be stuck doing multiples of 16 which isn’t fun.

    pure genius

  • About #5, if you do that you loose the “natural spacing” that all elements have in the browser. That means that two paragraphs following each other won’t have the natural spacing that the user might expect so you’ll have to manually add this yourself.

    If you’re working on large’ish site you as a CSS designer can’t predict all the kind of HTML use there will be on future pages. Sooner or later someone will try to edit a page but all padding has gone away. I’ve seen this many times and I hate it.

    Don’t f**k around too much with the way browsers work. If you break the conventions of spacing in what always matters the most, content, you’ll end up annoying the readers because it feels unfamiliar.

    My 2c

  • Hi Ben, very interesting and helpful info for a starting webmaster, working hard to make my site attractive and professional looking. Thanks (from another Ben…)

  • well, * { margin: 0; padding: 0; } is great, but I use more:

    img {border:0}

    and my top-notch:

    br {display:none}

    This is not a joke. It helps in some cases for alining up lines.

  • I think Kelly is right.

    To set the font-size percentage requires that every user’s standard font-size is 16px. But in many cases it is not.

    So I prefer Kelly’s way

  • I use * a lot. I use it mostly to set the base font of the document since doesn’t cascade into tables. That way you only define your font-family and “regular” text size once and then take care of the exceptions.

    You can also make your CSS “sections” more obvious by expanding the comments to include an underline:

    /* List Styles
    —————————————————- */

  • Can you explain why I should use 62.5% as the base font size instead of 76% as mentioned in http://www.thenoodleincident.com/tutorials/box_lesson/font/ or even setting 10px as the base font and use percents to resize the base font as mentioned by someone else?

    They all seem equally convincing but I feel completely and utterly confused.

    While I applaud your message about the 62.5% base font size but it doesn’t make me want to use it due to other conflicting methods of font resizing.

    By the way, 62.5% doesn’t always equate to 10px as a LOT of people will think. It is relative to 100% (whatever size the browser defaults dictates, not 16px but it does convincingly look like 16px).

  • 1) While non-pixel based font sizing is definitely the way to write your css, there is one (IE) caveat. If you set the font-size of the body below 100%, IE has a problem with text-zooming. The work-around is to set your body to 100% explicitly and 62,5% on your div-container (or similar div).,/i>

    Could you clarify this (with actual css code)? Thx.

  • D. Woods wrote:
    “Please don’t define the same tag/class/id/etc. multiple tmes under different sections…. it can become extraordinarily confusing when you think you’ve “foundâ€? the style definition you want to edit, and not realize you’re not seeing the whole definition”

    This makes sense within a single style sheet but we are, after all, dealing with *cascading* style sheets. You can not expect to find the “whole definition” in one place. You must analyse the cascade in reverse to find and change the property you are interested in.

  • Some nice points there. But I’d like to nit-pick :)

    (q)There is a trick […] that resets the font sizes for the entire site so that 1.0em is the same as 10px.(/q)

    Not necessarily. IE6 on my laptop shows 1em as 20px, rendering 62.5% as 12 or 13 pixels. That’s with factory settings. Text size is easily overridden in several ways by any visitor to your page. Also be aware that this technique may lead to considerable inconsistencies among browsers in applying visitor font-size preferences. See the charts on this page:
    http://www.gunlaug.no/contents/wd_1_03_04.html

    (q)Style everything at once […]
    * { margin: 0; padding: 0; }
    (/q)

    I’ve never seen the point of this. Most elements have zero margins and padding anyway. Almost all that have them need _some_ margin or padding, so why not just specify what you want and be done with it? Also note SU’s comment.

    KELLY – Your suggestion to use pixels for the BODY selector would be fine except for a bug in IE5 and 6 that prevents visitors to your page changing the text size using the View -> Text Size menu.

    ADAM – I’m not sure what we can do about those line-height bugs. Specifying units definitely has a down side. Let’s hope Gecko owners upgrade frequently.

  • For organizing your CSS, write your attributes in alphabetical order.

    For example, border will always come before margin which comes before width. It makes the CSS easier to scan and debug.

    Create a table of contents at the top of your CSS file that shows what sections your CSS is broken down into. Then you can just highlight a section and hit F3 (Win) to jump to it.

    For optimizing your CSS – don’t forget to combine classes. I wrote a post on this here: http://www.smileycat.com/miaow/archives/000152.html

  • Again, nice little list (please do more things like this!).

    But one thing I don’t understand is what exactly the tag does. I’ve looked in many places and I really don’t understand why people use it. I know it’s for some type of heading but I really don’t understand, could someone explain for me?

  • Hey,

    CSS is always one of the areas I never touched on, until in the past few months. I’m still learning, and I need to get more experience in the process.

    On a sidenote, this tutorial is great – before I’d even finished reading i’d hit the bookmark button in Safari.

    Awesome :-D
    Richard

Scroll To Top