CSS tips and tricks

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.

/* 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.

Comments

  1. says

    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. :)

  2. Su says

    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.

  3. says

    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.

  4. says

    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.

  5. says

    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

  6. Brian says

    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.

  7. says

    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)

  8. says

    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

  9. says

    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

  10. says

    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

  11. says

    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…)

  12. says

    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.

  13. Nick says

    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

  14. Stamp says

    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
    —————————————————- */

  15. Martin says

    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).

  16. Jeff says

    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.

  17. davidp says

    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.

  18. says

    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.

  19. says

    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

  20. Tim says

    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?

  21. says

    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

Trackbacks

  1. […] Via Digg i found this posting about restyling your CSS (Cascading Style Sheets). So.. let’s see if i can rewrite the already changed css file from the Qwilm! WordPress theme. (Others have changed it into this (also took a look at his plugins and themes), this, this, this, this, this, this or this. (Ok…ok… and this, this, this, this, this, …) (Maybe i should start a “I use Qwilm! webring). […]

  2. […] • A large resource of specifications, tutorials, and examples at the w3c website • CSS Tutorial at W3CSchools.com • CSSZenGarden: Great examples of what can be done when CSS is used right • Wikipedia knows everything, even CSS • CSS tips and tricks at The Blog Herald • CSSPlay: A huge gallery of CSS being used right • Quiet possibly the largest collection of CSS and design resources on the web • Beginner’s guide to CSS by Cameron Moll • CSS cheat sheet […]

  3. […] CSS tips and tricks at The Blog Herald “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 s (tags: css browser design) […]

  4. […] Our best months at The Blog Herald have been when we’re clicking on all eight cylinders and everyone is posting frequently. Traffic goes up, pageviews go up, ad revenues go up, and so on. Great content helps as well – and so does strong viral content like Ben’s post last month about CSS Tips & Tricks. […]

  5. […] Page Summary: Now you can use ems to sizes your fonts rather than pixels. 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. 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. If you set the font-size of the body below 100%, IE has a problem with text-zooming.read more | digg story              […]

  6. […] 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. Examples: /* Structure */, /* Typography */ etc.” [CSS Tips and Tricks] […]

  7. […] 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. Examples: /* Structure */, /* Typography */ etc.” [CSS Tips and Tricks] […]

  8. […] 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. Examples: /* Structure */, /* Typography */ etc.” [CSS Tips and Tricks] […]

  9. […] 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. Examples: /* Structure */, /* Typography */ etc.” [CSS Tips and Tricks] […]

  10. […] 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. Examples: /* Structure */, /* Typography */ etc.” [CSS Tips and Tricks] […]

  11. […] an Easier CSS Life E-mail is not a platform for design Top 10 CSS Tutorials Digital Web Magazine CSS tips and tricks Publicerades: 2007-06-27  |  Kategori: Länktips  |  Respons: Inga kommentarer […]

  12. […] 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. Examples: /* Structure */, /* Typography */ etc.” [CSS Tips and Tricks] […]

  13. […] 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. Examples: /* Structure */, /* Typography */ etc.” [CSS Tips and Tricks] […]

  14. […] 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. Examples: /* Structure */, /* Typography */ etc.” [CSS Tips and Tricks] […]

  15. […] Разделяйте код на блоки. Для многих это очевидно, но иногда я все же встречаю CSS не разделенные на блоки. Эта не сложная операция значительно упрощает работу с кодом недели, месяцы и годы спустя. Примеры: /* Structure */, /* Typography */ etc.” [CSS Tips and Tricks] […]

  16. […] the time – christianmontoya.com CSS Techniques Roundup – 20 CSS Tips and Tricks – petefreitag.com CSS tips and tricks – blogherald.com CSS: Getting Into Good Coding Habits – communitymx.com Erratic Wisdom: 5 Tips for […]

  17. […] 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. Examples: /* Structure */, /* Typography */ etc.” [CSS Tips and Tricks] […]

  18. […] 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. Examples: /* Structure */, /* Typography */ etc.” [CSS Tips and Tricks] […]

  19. […] 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. Examples: /* Structure */, /* Typography */ etc.” [CSS Tips and Tricks] […]

  20. […]  Move the codes 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..”  [CSS tips and tricks] […]

  21. […] 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. Examples: /* Structure */, /* Typography */ etc.” [CSS Tips and Tricks] […]

  22. […] 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. Examples: /* Structure */, /* Typography */ etc.” [CSS Tips and Tricks] […]

  23. […] 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. Examples: /* Structure */, /* Typography */ etc.” [CSS Tips and Tricks] […]

  24. […] time – christianmontoya.com – CSS Techniques Roundup – 20 CSS Tips and Tricks – petefreitag.com – CSS tips and tricks – blogherald.com – CSS: Getting Into Good Coding Habits – communitymx.com – Erratic Wisdom: 5 Tips […]

  25. […] 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. Examples: /* Structure */, /* Typography */ etc.” [CSS Tips and Tricks] […]