share
Stack OverflowWhat CSS tips should every beginning developer know about?
[+46] [11] splattne
[2009-02-01 13:42:51]
[ css ]
[ http://stackoverflow.com/questions/500827/what-css-tips-should-every-beginning-developer-know-about ] [DELETED]

I'm compiling a list of the most important things beginning web developers should know about Cascading Style Sheets.

I'm looking for good practices, commonly misused or misunderstood concepts or other simply useful tips for newbies. For example:

What other important advice should my list contain?

(5) Please make this a wiki. - Binoj Antony
[+37] [2009-02-01 16:52:46] Ross [ACCEPTED]

Install Firebug

I did not understand the box model (or even the DOM) properly until I took a look at Firebug's box model diagram. It's very useful to know what's going on with an element.

Comment regularly

It's not nice going over code again to find that actually, you can't remember what this particular class does, or where it's used.

@-rules

@import

I import stylesheets all the time. A good way of doing things is to make a stylesheet for a specific type of layout, that imports a reset, a global typography sheet, etc.

@media

While you can specify different stylesheets for different mediums (using media="screen" in the link) @media can be useful for short declarations.

Learn the typical tricks

The tricks we all end up using to get something right. These can include:

Try some CSS frameworks

Probably not recommended for beginners but for intermediate-advanced programmers looking at other people's code can be very useful. Most are grid related, but I'd recommend YUI and 960.

[1] http://www.quirksmode.org/css/clearing.html
[2] http://www.alistapart.com/articles/sprites2
[3] http://www.alistapart.com/articles/sprites
[4] http://www.alistapart.com/articles/fauxcolumns
[5] http://www.alistapart.com/articles/slidingdoors
[6] http://www.alistapart.com/articles/multicolumnlayouts
[7] http://www.alistapart.com/articles/howtosizetextincss
[8] http://www.alistapart.com/articles/relafont
[9] http://www.alistapart.com/topics/code/css/

(7) do not @import if you don't have to, and for the love of god do not use CSS frameworks - Jason
1
[+22] [2009-02-01 16:34:09] facildelembrar

Always use a doctype that triggers standards mode. This will make your page behave more consistently across browsers. Some doctypes you can use are:

html 5
<!DOCTYPE html>
html 4.01 strict
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
xhtml 1.0 strict
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
xhtml 1.1
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

Always validate your markup, because if it has errors, browsers will switch to "quirksmode" even if you use a standards mode doctype. You can validate your markup with the w3c validator [1] or the wdg validator [2].

Use a set of CSS rules to reset cross browser inconsistencies. Each browser may have different default values for some settings, like margins and fonts sizes. I usually put this on the beginning of my main stylesheet to avoid unwanted "holes" in my layout:

html * { margin: 0; padding: 0; }

It's a very simple CSS reset that will save you from a lot of troubles, but you might need a more complete solution like yahoo!'s [3].

Always use external stylesheets for performance and maintainability issues.

Know the priority of selectors and rules. This will save you many headaches. More specific selectors have greater priority. This means their rules cannot be overridden by selectors with lesser priority.

Id selectors (#someId {...}) have priority over class selectors (.someClass {...}), which in turn have priority over tag selectors (p {...}). Then, nested selectors (div p {...}) have greater priority over simple selectors (p {...}). And finally, if you're dealing with two different selectors of the same type (ex. two class selectors), the one that appears last has greater priority.

After you've mastered these, look out for "classitis" and "divitis".

[1] http://validator.w3.org/
[2] http://htmlhelp.com/tools/validator/
[3] http://developer.yahoo.com/yui/reset/

(1) To bolt onto that, selectors work on scoring. Ids are 100, classes are usually 1 and tags are usually 10. !important boosts it up by a large number. - Ross
+1 Nice post. I hadn't actually seen the Yahoo reset css before - cletus
That's an awful reset!. I would definitely recommend the Yahoo one, or the one I use, Eric Meyer's. - alex
'(...) if it has errors, browsers will switch to "quirksmode" even if you use a standards mode doctype' is not true. - mercator
just to correct Ross above, it doesn't quite work like that. in order of importance it's: inline styles, IDs, classes, tags, pseudo-classes (eg :hover). No matter how many classes are used to specify an element, this will always get overriden by an element specified by ID - wheresrhys
One more thing about selectors and inline styles. They get overridden by html attributes. For instance, the attribute bgcolor="..." overrides the inline attribute style="background-color..." - facildelembrar
2
[+12] [2010-10-13 18:44:27] c4il

I didn't know about this fact until today, and I was thinking exactly the opposite!

That, Browsers evaluate the selector rules from right to left.

Quote from Steve Souders's blog [1].

Here’s a much more expensive selector: A.class0007 * { }. Although this selector might look simpler, it’s more expensive for the browser to match. Because the browser moves right to left, it starts by checking all the elements that match the key selector, “*“. This means the browser must try to match this selector against all elements in the page.

[1] http://www.stevesouders.com/blog/2009/06/18/simplifying-css-selectors/

3
[+11] [2009-02-01 13:46:25] JacquesB
  • Understand the layers of the box-model [1].

    Note that paddings are cumulative, while margins collapse (i.e. the distance between two adjacent boxes is the largest of the two margins - not the sum of both margins.)

  • Remember to use a doctype [2] that triggers standards mode. Note that the doctype must be the first tag - a comment or XML-declaration before the doctype may (or may not, depending on the browser) trigger quirks mode.

[1] http://arston.com/wp-content/uploads/2007/04/3d-box-model.png
[2] http://www.alistapart.com/articles/doctype/

4
[+8] [2009-02-01 13:45:39] innaM

Make sure your HTML is valid before you ask yourself why your CSS isn't working in every browser.


5
[+8] [2009-02-01 17:16:59] VirtuosiMedia

There are certainly hundreds of tips that could go here, but the biggest one I can write is to be prepared to deal with Internet Explorer 6. IE6 has roughly 20% market share, so it can't be ignored. However, it also is probably one of the biggest problems for web developers.

I develop first for Firefox, Safari, Opera, and Chrome (which are all standards-compliant browsers). Once it's working with them, I move on to IE7, and finally IE6. Here are some specific tips that might help you:

  • I validate both my XHTML and CSS.
  • I keep my designs simple, even the complicated ones.
  • I don't use hacks that invalidate my CSS.
  • I use a JavaScript framework/library (I like MooTools, but you'll get a lot of votes for jQuery, Prototype, YUI, Dojo, and many others) that handles most of my cross-browser JavaScript problems.
  • I progressively enhance my pages so that they first work without JavaScript and then add all the bells and whistles.
  • For some of the double margin problems, I use display:inline;
  • If I absolutely have to, I use a separate stylesheet, though I'm finding I have to do this less and less.
  • I try to avoid transparent images in my layouts. If I absolutely need them, I use a PNG8 with alpha transparency, which IE6 actually does support.
  • To get at the min-height problem, I do the following:

This for IE6, which incorrectly interprets height as min-height:

.classNameHere {height:300px;}

This for for everything else:

div>div .classNameHere {min-height:300px; height:auto;}

Other general tips would include:

  • Always use external stylesheets in production.
  • Use CSS sprites.
  • Use a script to combine and minify your different stylesheets
  • Use CSS images for any layout images, use an HTML img tag for images that are a part of the content.
  • Use the YSlow [1] tool and Firebug [2].
  • Name your CSS classes and IDs after their purpose, not their appearance. Appearance can and will change, so after a few edits, .redColumn isn't going to tell you anything. .sidebar would be more appropriate.
  • Comment and group similar classes and IDs. I generally group by layout, forms, typography, menu, etc.
  • Learn by copying. If you see a design you absolutely love, try to replicate it (for learning purposes only). It's great practice and you'll learn a lot. CSS Zen Garden [3] is a great place to start.
  • Design your layouts so that they are flexible. Look at your design at different resolutions. Readers can also resize text, so see how text resizing affects your layout. Plan accordingly.
  • Don't get discouraged. It will take some time and practice before you really start to get the hang of it.
[1] http://developer.yahoo.com/yslow/
[2] http://getfirebug.com/
[3] http://www.csszengarden.com/

(1) Nice answer, thanks! - splattne
(1) I'd actually vote against CSS Zen Garden. Most of the designs there are way too heavily reliant on images and so it's difficult for a CSS beginner to start there. - Lotus Notes
6
[+6] [2009-03-18 09:40:36] splattne

CSS Selectors

Whereas HTML has tags, CSS has 'selectors'. Selectors are the names given to styles in internal and external style sheets. CSS HTML selectors are simply the names of HTML tags and are used to change the style of a specific tag:

td {
    font-size: 0.8em;
    color: green;
}

Properties

For each selector there are properties inside curly brackets, which simply take the form of words such as color, font-weight or background-color.

Values

A value is given to the property following a colon ":" and semi-colons ";" separate the properties.

Ways to apply CSS to HTML

There are three different ways to apply CSS to HTML.

In-line

In-line styles can be assigned straight into the HTML tags using the style attribute:

 <p style="color: blue">example</p>

Internal

Embedded, or internal styles are used for the whole page. Inside the head tags, the style tags surround all of the styles for the page.

...
<html>
<head>
   <title>Example Page</title>
   <style type="text/css">
      h1 { color: green }
      h2 { color: red   }
   </style>
...

External

External styles are used for the whole, multiple-page website. There is a separate CSS file:

...
<head>
   <title>Example Page</title>
   <link rel="stylesheet" type="text/css" href="web.css" />
...

The best-practice approach though is that the HTML should be a stand-alone, presentation free document, and so in-line styles should be avoided wherever possible.


7
[+4] [2009-02-01 13:51:47] code-o-mat

Do tests in all relevant browsers at short intervals right from the beginning. Ironing things out afterwards is a lot harder and more time-consuming.


8
[+2] [2009-02-01 13:46:03] cjk

Don't create a class for every element. Create one for each type.

I have an application I've inherited at work, and rather than style all the buttons with a class, each one has its own descriptive class, which means I have to change 20+ classes to change what the buttons look like.

Also, name your classes independently of their actual style, e.g. .leftcolumn rather than .greenleftcolumn etc.


‘leftcolumn’ is still pretty dependent on its style! :-) Something like ‘navarea’ might be better if you plan to allow the CSS to change the layout. - bobince
I'm curious, does that mean the 20 buttons all use a separate class, but each class has the exact same code? - Billworth Vandory
@Billworth - pretty much, yes. There were one or two differences in some of them, but the majority were identical. - cjk
9
[+2] [2009-02-01 13:47:55] Kb.
10
[0] [2009-02-03 20:52:40] JoshFinnie

Definitely validate your HTML before moving forward with your CSS.

Use direct links (http://example.com/css/style.css) instead of local links when importing your CSS.


11