30 CSS Best Practices for Beginners

30 CSS Best Practices for Beginners – Basix

Sep 16th in HTML & CSS by Glen Stansberry

CSS is a language that is used by nearly every developer at some point. While it's a language that we sometimes take for granted, it is powerful and has many nuances that can help (or hurt) our designs. Here are thirty of the best CSS practices that will keep you writing solid CSS and avoiding some costly mistakes.

PG

Author: Glen Stansberry

Glen Stansberry is a web developer and blogger. You can read more tips on web development at his blog Web Jackalope or follow him on Twitter.

1. Make it Readable

The readability of your CSS is incredibly important, though most people overlook why it's important. Great readability of your CSS makes it much easier to maintain in the future, as you'll be able to find elements quicker. Also, you'll never know who might need to look at your code later on.

<editors-note> When writing CSS, most developers fall into one of two groups.

Group 1: All on one line

.someDiv { background: red; padding: 2em; border: 1px solid black; }

Group 2: Each style gets its own line

.someDiv {
  background: red;
  padding: 2em;
  border: 1px solid black;
}

Both practices are perfectly acceptable, though you'll generally find that group two despises group one! Just remember - choose the method that looks best TO YOU. That's all that matters. </editors-note>

2. Keep it Consistent

Along the lines of keeping your code readable is making sure that the CSS is consistent. You should start to develop your own "sub-language" of CSS that allows you to quickly name things. There are certain classes that I create in nearly every theme, and I use the same name each time. For example, I use ".caption-right" to float images which contain a caption to the right.

Think about things like whether or not you'll use underscores or dashes in your ID's and class names, and in what cases you'll use them. When you start creating your own standards for CSS, you'll become much more proficient.

3. Start with a Framework

Some design purists scoff at the thought of using a CSS framework with each design, but I believe that if someone else has taken the time to maintain a tool that speeds up production, why reinvent the wheel? I know frameworks shouldn't be used in every instance, but most of the time they can help.

Many designers have their own framework that they have created over time, and that's a great idea too. It helps keep consistency within the projects.

CSS frameworks

<editors-note> I disagree. CSS frameworks are fantastic tools...for those who know how to use them.

It's less a matter of reinventing the wheel, and more a matter of understanding how the wheel works.

If you're just getting started with CSS, I'd personally recommend that you stay away from these frameworks for at least a year. Otherwise, you'll only confuse yourself. Learn CSS...then take shortcuts! </editors-note>

4. Use a Reset

Most CSS frameworks have a reset built-in, but if you're not going to use one then at least consider using a reset. Resets essentially eliminate browser inconsistencies such as heights, font sizes, margins, headings, etc. The reset allows your layout look consistent in all browsers.

The MeyerWeb is a popular reset, along with Yahoo's developer reset. Or you could always roll your own reset, if that tickles your fancy.

5. Organize the Stylesheet with a Top-down Structure

It always makes sense to lay your stylesheet out in a way that allows you to quickly find parts of your code. I recommend a top-down format that tackles styles as they appear in the source code. So, an example stylesheet might be ordered like this:

  1. Generic classes (body, a, p, h1, etc.)
  2. #header
  3. #nav-menu
  4. #main-content

<editors-note> Don't forget to comment each section! </editors-note>

/****** main content *********/

styles goes here...

/****** footer *********/

styles go here...

6. Combine Elements

Elements in a stylesheet sometimes share properties. Instead of re-writing previous code, why not just combine them? For example, your h1, h2, and h3 elements might all share the same font and color:

	h1, h2, h3 {font-family: tahoma, color: #333}

We could add unique characteristics to each of these header styles if we wanted (ie. h1 {size: 2.1em}) later in the stylesheet.

7. Create Your HTML First

Many designers create their CSS at the same time they create the HTML. It seems logical to create both at the same time, but actually you'll save even more time if you create the entire HTML mockup first. The reasoning behind this method is that you know all the elements of your site layout, but you don't know what CSS you'll need with your design. Creating the HTML layout first allows you to visualize the entire page as a whole, and allows you to think of your CSS in a more holistic, top-down manner.

8. Use Multiple Classes

Sometimes it's beneficial to add multiple classes to an element. Let's say that you have a <div> "box" that you want to float right, and you've already got a class .right in your CSS that floats everything to the right. You can simply add an extra class in the declaration, like so:

	<div class="box right"></div>

You can add as many classes as you'd like (space separated) to any declaration.

<editors-note> Be very careful when using ids and class-names like "left" and "right." I will use them, but only for things such as blog posts. How come? Let's imagine that, down the road, you decide that you'd rather see the box floated to the LEFT. In this case, you'd have to return to your HTML and change the class-name - all in order to adjust the presentation of the page. This is unsemantic. Remember - HTML is for markup and content. CSS is for presentation.

If you must return to your HTML to change the presentation (or styling) of the page, you're doing it wrong!

</editors-note>

9. Use the Right Doctype

The doctype declaration matters a whole lot on whether or not your markup and CSS will validate. In fact, the entire look and feel of your site can change greatly depending on the DOCTYPE that you declare.

Learn more about which DOCTYPE to use at A List Apart.

doctype

<editors-note>

I use HTML5's doctype for all of my projects.

<!DOCTYPE html>

"What's nice about this new DOCTYPE, especially, is that all current browsers (IE, FF, Opera, Safari) will look at it and switch the content into standards mode - even though they don't implement HTML5. This means that you could start writing your web pages using HTML5 today and have them last for a very, very, long time."

</editors-note>

10. Use Shorthand

You can shrink your code considerably by using shorthand when crafting your CSS. For elements like padding, margin, font and some others, you can combine styles in one line. For example, a div might have these styles:

	#crayon {
		margin-left:	5px;
		margin-right:	7px;
		margin-top:	8px;
	}

You could combine those styles in one line, like so:

	#crayon	{
		margin: 8px 7px 0px 5px; // top, right, bottom, and left values, respectively.
	}

If you need more help, here's a comprehensive guide on CSS shorthand properties.

11. Comment your CSS

Just like any other language, it's a great idea to comment your code in sections. To add a comment, simply add /* behind the comment, and */ to close it, like so:

	/* Here's how you comment CSS */

12. Understand the Difference Between Block vs. Inline Elements

Block elements are elements that naturally clear each line after they're declared, spanning the whole width of the available space. Inline elements take only as much space as they need, and don't force a new line after they're used.

Here are the lists of elements that are either inline or block:

span, a, strong, em, img, br, input, abbr, acronym

And the block elements:

div, h1...h6, p, ul, li, table, blockquote, pre, form

13. Alphabetize your Properties

While this is more of a frivolous tip, it can come in handy for quick scanning.

	#cotton-candy {
		color: #fff;
		float: left;
		font-weight:
		height: 200px;
		margin: 0;
		padding: 0;
		width: 150px;
	}
<editors-note> Ehh... sacrifice speed for slightly improved readability? I'd pass - but decide for yourself! </editors-note>

14. Use CSS Compressors

CSS compressors help shrink CSS file size by removing line breaks, white spaces, and combining elements. This combination can greatly reduce the the file size, which speeds up browser loading. CSS Optimizer and CSS Compressor are two excellent online tools that can shrink CSS.

It should be noted that shrinking your CSS can provide gains in performance, but you lose some of the readability of your CSS.

use css compressors

15. Make Use of Generic Classes

You'll find that there are certain styles that you're applying over and over. Instead of adding that particular style to each ID, you can create generic classes and add them to the IDs or other CSS classes (using tip #8).

For example, I find myself using float:right and float:left over an over in my designs. So I simply add the classes .left and .right to my stylesheet, and reference it in the elements.

	.left {float:left}
	.right {float:right}
	
	<div id="coolbox" class="left">...</div>

This way you don't have to constantly add "float:left" to all the elements that need to be floated.

<editors-note> Please refer to editor's notes for #8. </editors-note>

16. Use "Margin: 0 auto" to Center Layouts

Many beginners to CSS can't figure out why you can't simply use float: center to achieve that centered effect on block-level elements. If only it were that easy! Unfortunately, you'll need to use

	margin: 0 auto; // top, bottom - and left, right values, respectively.

to center divs, paragraphs or other elements in your layout.

<editors-note> By declaring that both the left AND the right margins of an element must be identical, the have no choice but to center the element within its containing element. </editors-note>

17. Don't Just Wrap a DIV Around It

When starting out, there's a temptation to wrap a div with an ID or class around an element and create a style for it.

	<div class="header-text"><h1>Header Text</h1></div>

Sometimes it might seem easier to just create unique element styles like the above example, but you'll start to clutter your stylesheet. This would have worked just fine:

	<h1>Header Text</h1>

Then you can easily add a style to the h1 instead of a parent div.

18. Use Firebug

If you haven't downloaded Firebug yet, stop and go do it. Seriously. This little tool is a must have for any web developer. Among the many features that come bundled with the Firefox extension (debug JavaScript, inspect HTML, find errors), you can also visually inspect, modify, and edit CSS in real-time. You can learn more about what Firebug does on the official Firebug website.

use firebug

19. Hack Less

Avoid using as little browser-specific hacks if at all possible. There is a tremendous pressure to make sure that designs look consistent across all browsers, but using hacks only makes your designs harder to maintain in the future. Plus, using a reset file (see #4) can eliminate nearly all of the rendering irregularities between browsers.

20. Use Absolute Positioning Sparingly

Absolute positioning is a handy aspect of CSS that allows you to define where exactly an element should be positioned on a page to the exact pixel. However, because of absolute positioning's disregard for other elements on the page, the layouts can get quite hairy if there are multiple absolutely positioned elements running around the layout.

21. Use Text-transform

Text-transform is a highly-useful CSS property that allows you to "standardize" how text is formatted on your site. For example, say you're wanting to create some headers that only have lowercase letters. Just add the text-transform property to the header style like so:

text-transform: lowercase;

Now all of the letters in the header will be lowercase by default. Text-transform allows you to modify your text (first letter capitalized, all letters capitalized, or all lowercase) with a simple property.

22. Don't use Negative Margins to Hide Your h1

Oftentimes people will use an image for their header text, and then either use display:none or a negative margin to float the h1 off the page. Matt Cutts, the head of Google's Webspam team, has officially said that this is a bad idea, as Google might think it's spam.

As Mr. Cutts explicitly says, avoid hiding your logo's text with CSS. Just use the alt tag. While many claim that you can still use CSS to hide a h1 tag as long as the h1 is the same as the logo text, I prefer to err on the safe side.

23. Validate Your CSS and XHTML

Validating your CSS and XHTML does more than give a sense of pride: it helps you quickly spot errors in your code. If you're working on a design and for some reason things just aren't looking right, try running the markup and CSS validator and see what errors pop up. Usually you'll find that you forgot to close a div somewhere, or a missed semi-colon in a CSS property.

24. Ems vs. Pixels

There's always been a strong debate as to whether it's better to use pixels (px) or ems (em) when defining font sizes. Pixels are a more static way to define font sizes, and ems are more scalable with different browser sizes and mobile devices. With the advent of many different types of web browsing (laptop, mobile, etc.), ems are increasingly becoming the default for font size measurements as they allow the greatest form of flexibility. You can read more about why you should use ems for font sizes in this thoughtful forum thread. About.com also has a great article on the differences between the measurement sizes.

<editors-note>Don't take me to the farm on this one - but I'd be willing to bet that, thanks to browser zooming, the majority of designers are defaulting to pixel based layouts. What do you think? </editors-note>

25. Don't Underestimate the List

Lists are a great way to present data in a structured format that's easy to modify the style. Thanks to the display property, you don't have to just use the list as a text attribute. Lists are also great for creating navigation menus and things of the sort.

Many beginners use divs to make each element in the list because they don't understand how to properly utilize them. It's well worth the effort to use brush up on learning list elements to structure data in the future.

<editors-note>

You'll often see navigation links like so:

 Home
 About
 Services
 Contact

Though, technically, this will work just fine after a bit of CSS, it's sloppy. If you're adding a list of links, use an unordered list, silly goose!

</editors-note>

26. Avoid Extra Selectors

It's easy to unknowingly add extra selectors to our CSS that clutters the stylesheet. One common example of adding extra selectors is with lists.

body #container .someclass ul li {....}
In this instance, just the .someclass li would have worked just fine.
.someclass li {...}

Adding extra selectors won't bring Armageddon or anything of the sort, but they do keep your CSS from being as simple and clean as possible.

27. Add Margins and Padding to All

Different browsers render elements differently. IE renders certain elements differently than Firefox. IE 6 renders elements differently than IE 7 and IE 8. While the browsers are starting to adhere more closely to W3C standards, they're still not perfect (*cough IE cough*).

One of the main differences between versions of browsers is how padding and margins are rendered. If you're not already using a reset, you might want to define the margin and padding for all elements on the page, to be on the safe side. You can do this quickly with a global reset, like so:

	* {margin:0;padding:0;}

Now all elements have a padding and margin of 0, unless defined by another style in the stylesheet.

<editors-note> The problem is that, because EVERYTHING is zeroed out with this method, you'll potentially cause yourself more harm than help. Are you sure that you want every single element's margins and padding zeroed? If so - that's perfectly acceptable. But at least consider it. </editors-note>

28. When Ready, Try Object Oriented CSS

Object Oriented programming is the separation of elements in the code so that they're easier to maintain reuse. Object Oriented CSS follows the same principle of separating different aspects of the stylesheet(s) into more logical sections, making your CSS more modular and reusable.

Here's is a slide presentation of how Object Oriented CSS works:

If you're new to the CSS/XHTML game, OOCSS might be a bit of a challenge in the beginning. But the principles are great to understand for object oriented programming in general.

29. Use Multiple Stylesheets

Depending on the complexity of the design and the size of the site, it's sometimes easier to make smaller, multiple stylesheets instead of one giant stylesheet. Aside from it being easier for the designer to manage, multiple stylesheets allow you to leave out CSS on certain pages that don't need them.

For example, I might having a polling program that would have a unique set of styles. Instead of including the poll styles to the main stylesheet, I could just create a poll.css and the stylesheet only to the pages that show the poll.

<editors-note> However, be sure to consider the number of HTTP requests that are being made. Many designers prefer to develop with multiple stylesheets, and then combine them into one file. This reduces the number of HTTP requests to one. Also, the entire file will be cached on the user's computer. </editors-note>

30. Check for Closed Elements First When Debugging

If you're noticing that your design looks a tad wonky, there's a good chance it's because you've left off a closing </div>. You can use the XHTML validator to help sniff out all sorts of errors too.

You Might Also Enjoy...


Related Posts

Check out some more great tutorials and articles that you might like

Enjoy this Post?

Your vote will help us grow this site and provide even more awesomeness

Plus Members

Source Files, Bonus Tutorials and
More for $9 a month for all TUTS+
sites in one subscription.

Join Now

User Comments

( ADD YOURS )
  1. PG

    Stoian Kirov September 16th

    Great tips! Thank you! :)

    ( Reply )
  2. PG

    Jeffrey Way September 16th

    Guys – just ignore the “rightright” and “bottombottom.” It’s a bug in the code highlighter plugin we use.

    ( Reply )
    1. PG

      Dean September 16th

      What about the and tags?

      ( Reply )
    2. PG

      Dean September 16th

      The code didnt show.
      I meant “editors-note” tags

      ( Reply )
      1. PG

        NickyB September 16th

        Those were purposefully left from what I can tell. It was meant for us to know that the editor thinks differently from the author as I noted in my own comment.

      2. PG

        Jeffrey Way September 16th

        @Dean – was just a silly way to designate that I was writing…and not the author, Glen. :)

      3. PG

        Ian O'Dea September 16th

        The editors-note tags are there on purpose to identify that they are added afterward by the editor, as opposed to being part of the author’s content.

    3. PG

      Meshach September 16th

      I like the tag. You should approach w3c about including it in HTML5.

      ( Reply )
    4. PG

      Furley September 16th

      let’s squash that bug already!

      ( Reply )
  3. PG

    NickyB September 16th

    Hmmm a lot of Editor thoughts make this seem more like a debate since they say the opposite of what the author has said. Though both points may be valid I would suggest in the future suggesting the addition of those items to the author instead of going the route this article made.

    Other than that I enjoyed reading the article and I can see where I can use a lot of those suggestions to fix some glaring mistakes.

    ( Reply )
    1. PG

      Jeffrey Way September 16th

      I considered that as well. However, in the design world, “best practices” is a very vague term. I personally find it helpful to review what too different people think on a subject.

      But point well taken. :)

      ( Reply )
      1. PG

        Helen September 17th

        The editor was right in every remark he made. I have another one refering to #8 and #15: These tips are trying to blow up the mark-up with class-names (with every class having one property only) instead of taking advantage of the cascading nature of CSS (enhanced by pseudo-classes). But this way is just an outsourced variant inline-styling. There is no big difference besides writing “class=…” in the mark-up instead of “style=…”

        You will have to clean all that mess in a hundred html-pages in a future relaunch instead of just making one change in the CSS.

      2. PG

        Singh September 27th

        understood, however it really lowered the credibility of the original author, and felt like you wanted to just write the whole tutorial yourself jeff

    2. PG

      Rachel Reveley September 24th

      I liked the editor notes, they added a little humour and helped to show that not everyone thinks the same way about best practices and prevented what would have been a “This is what you should do and that’s final” type of article.

      Also thanks for the css optimiser links.

      ( Reply )
  4. PG

    Juan C Rois September 16th

    This is great information for designers/developer that are just starting to learn. I wish I would have found articles like this (maybe I did not look hard enough) when I started to code my websites, In fact after 5 years of doing this I realized just a few weeks ago that an element can have 2 or more classes. I guess that’s what happens when you just scan through the books instead of reading and understanding them.
    Hope many new designers/developers take the time to learn from articles like this and don’t make the same mistakes I did. Don’t cut corners and above all read and follow as many tutorials as possible.
    The end result will be much better.

    Thanks for the article Glen

    ( Reply )
  5. PG

    Eric Clemmons September 16th

    Let’s not forget that IE6 does not support multiple classes. becomes .

    ( Reply )
    1. PG

      NickyB September 16th

      IE what? Thats like Windows ME it doesn’t exist hehe… Make a prompt for every website you make that if so and so is using IE 6 it sends them to IE update instead…

      ( Reply )
      1. PG

        Ian O'Dea September 16th

        While it is certainly noble of you to tell your visitors to upgrade from IE6, you’ll lose a lot more than you convert.

      2. PG

        Robin Drost September 16th

        Many people still use IE 6 ;) They just dont know 8 is already out lol.

      3. PG

        NickyB September 16th

        @Ian O’Dea I meant that very sarcastically. I wouldn’t really push them away. If I didn’t anything like that I would have something telling them there is a better browser available for free download.

    2. PG

      Ant September 16th

      It’s support, just you should write div.one.two instead of .one.two

      ( Reply )
    3. PG

      NatalieMac September 17th

      IE6 supports multiple class names. The only feature of multiple class names not supported in IE6 is the ability to use chained class names in the css as a selector.

      If, for example this is your HTML:

      <div class=”box featured”><div>

      IE6 and the other common browsers will all recognize:
      .box {margin:10px; padding:10px; border: 1px solid purple;}
      .featured { background: pink; }

      IE6 won’t recognize .box.featured { border: 3px solid red;}

      But I find I rarely need to use multiple class names as a selector anyway.

      ( Reply )
  6. PG

    Bill September 16th

    Excellent information guys. Really, this is awesome. Wish this had been around when I first started.

    Thanks for sharing your knowledge! It’s sure appreciated.

    ( Reply )
  7. PG

    mment September 16th

    Great tipps! Primarily number 7!

    ( Reply )
    1. PG

      Nick September 16th

      I agree – this is something that is overlooked at first.

      ( Reply )
  8. If you use a reset, please don’t forget to define the default behavior of lists and other stuff that might otherwise be broken by the reset.

    It’s nice to have your navigation bar as a list and still look funky, but what if afterwards the client wants to put an actual list in their content?

    Also, don’t do this:
    input { width: 100%; }

    Do it only where you need it:
    #myStuff input { width: 100%; }

    ( Reply )
  9. PG

    Stephen Coley September 16th

    As for alphabetizing element styles…

    One thing completely turns me off to this practice – the fact that width and height wouldn’t be next to each other. I couldn’t do it. It would separate top and left in some cases as well.

    ( Reply )
    1. PG

      Meshach September 16th

      I think that alphabetizing CSS is absurd. :)

      ( Reply )
    2. PG

      Wes September 16th

      I alphabetize. I started a couple of months ago and cannot imagine going back. It makes scanning though css so much easier, especially if it is someone else’s css that is alphabetized.

      ( Reply )
    3. PG

      NickD September 16th

      Depending on the complexity of the CSS, sometimes I’ll break things out so the CSS attributes are in groupings. For example, height and width would be together, all font & text declarations together, positioning together. etc.

      For the most part though, I’ve ingrained alphabetizing the attributes into memory.

      Also, why is it absurd? It makes looking for specific attributes so much quicker… this comes in especially handy when all the attributes are on one line (at least for me).

      Oh and how does using alpha order affect speed, as the editor noted? I’ve not heard of any actual speed hit from this.

      ( Reply )
      1. PG

        Jazon September 16th

        I think the editor meant it takes more time order the attributes when you write it, rather than the time it takes for the browser to render it.

  10. PG

    เพชรร่วง September 16th

    thank you for a nice tutorial

    ( Reply )
  11. PG

    RussellUresti September 16th

    How does 22 apply to a negative text-indent? My typical H1 for the header will look something like this:

    HTML
    Company Name

    CSS
    h1 a {
    display: block;
    height: Ypx;
    width: Xpx;
    background: url(images/logo.jpg) no-repeat top center;
    text-indent: -9999px;
    }

    This way, it’s actual text instead of an image and alt text. Does this also count as a demerit for search engines?

    ( Reply )
    1. PG

      RussellUresti September 16th

      I was not expecting the h1 and a tag to actually compile there… let’s try that again.

      HTML
      {h1}{a href=”index.html”}Company Name{/a}{/h1}

      Curly brackets in use because the comment actually evaluated the code in the previous statement.

      ( Reply )
    2. PG

      Wes September 16th

      If search engine do demerit for negative text indented links, just put a span tag right inside the anchor tag and negative text indent it.

      Text

      h1 a span {
      display: block;
      height: Ypx;
      width: Xpx;
      background: url(images/logo.jpg) no-repeat top center;
      text-indent: -9999px;
      }

      Or you could give the anchor tag the height of the logo, set the padding to the height of the logo, set the background-image to the logo, and then hide the overflow. So basically you are pushing the readable text down below the displayed area. I think this is what Apple does if I remember correctly.

      ( Reply )
      1. PG

        Wes September 16th

        Ditto.

        {h1}{a href=”#”}{span}Text{/span}{/a}{/h1}

      2. PG

        RussellUresti September 16th

        Yep, I just checked, Apple sets the overflow to hidden and the padding-top to the height of the image, so the text is pushed below the overflow. Though they do it in an {li}{a} instead of an h1. I may make that my new methodology.

    3. PG

      Mirek September 16th

      In this case, what happens if someone has images disabled? And if there isn’t any print stylesheet, background images don’t print, do they? I’d prefer logo to be included if someone prints a page.

      ( Reply )
  12. PG

    Amber Weinberg September 16th

    LOL Great tips, although I disagree with quite a few. Funny thing is, I’m working on a clean CSS article for my own blog tomorrow

    ( Reply )
  13. What exactly do you mean, Eric Clemmons? The following does work under IE6 (at least for me):

    .c {
    font-weight: bold;
    background: #fff;
    }
    .a {
    color: red;
    }
    .b {
    background: yellow;
    }

    MOMO
    MOMO
    MOMO

    The span in the middle shows as expected, in red over yellow.

    ( Reply )
    1. PG

      NickD September 16th

      I think he’s referring to doing something like this:

      [p class="left blue"]

      and in the css using:

      .left { text-align:left; }
      .blue { color:blue; }
      .left.blue { text-align:right; color:red; }

      I can’t recall off hand, but IE6 will not make the paragraph have right aligned blue text. Instead it would have only blue text.

      That’s a very primitive example, but it should get the idea across…

      ( Reply )
  14. PG

    Ant September 16th

    Some more hints:

    – Use editor with syntax highlight, if you forgot to add quote or bracket, colours after error should go crazy (in Intype does).
    – Install html validator plugin for Firefox, it’s way faster than validating via site.
    – Sometimes is preferable to use
    #container .someclass li
    over
    .someplass li, if design is too complex (though I prefer simple designs)
    – don’t mind to use css3 rules, even if they not aviable for all browsers, people with modern ones would enjoy them.

    ( Reply )
  15. PG

    Jeff Dion September 16th

    Lot of nice tricks. I was glad to see editor’s edit which suits more my views of CSS for beginners.

    I would also add an other point

    #31 – Use the W3C validators for HTML/XHTML/HTML5 (
    http://validator.w3.org/) and CSS (http://jigsaw.w3.org/css-validator/) to debug and avoid a lot of troubles further down the line

    ( Reply )
  16. PG

    Jeff September 16th

    There was some good stuff in there, but some not-so-great stuff to. The editor did a good job.

    ( Reply )
  17. PG

    David Moreen September 16th

    CSS is one of the easiest languages to learn. Seriously, I just starting to use it on a wem and the only thing you need to do really…. Is to remember all of the different styles. Also I do not recommend frameworks ever (except javascript). You will learn a lot more if you learn raw code ;)

    ( Reply )
    1. PG

      James September 16th

      “except javascript” – why?

      ( Reply )
      1. PG

        Michele September 16th

        There are great Javascript frameworks out there that everyone uses because they are so good, and often lightweight. Think of jQuery.

    2. PG

      Jeffrey Way September 16th

      I think what James is asking is….why is it okay to use a great JavaScript framework like jQuery, but not a great framework like CodeIgniter?

      ( Reply )
      1. PG

        Siddharth September 17th

        It’s best to learn the core of a language and then move on to frameworks when you’ve mastered the language and want to cut down development time.

        Jumping on to a framework without knowing the language in question will make things that much more harder when something breaks and you have to fix it.

        Just my 0.02c.

  18. PG

    PibesdeMultimedia September 16th

    Muy buen artículo.
    Estoy de acuerdo con la nota del editor en cuanto a pensar como anda la rueda, antes de copiar y pegarla.

    Eso hoy en día se ve en muchos aspectos en ciencia, por ejemplo en física o matemática, los profesores se encuentran ante el dilema si enseñar toda la materia de la base o enseñar como usar un software que lo aplique.

    En mi opinión es mejor aprender como funciona primero, construyendo desde la base y aprendiendo, y luego aplicar profesionalmente alguna herramienta útil, que nos agilice el proceso.

    ( Reply )
  19. PG

    Matt September 16th

    Love the combination of opinions. Though, thanks for the OOCSS. I didn’t realize it was so easy to get started with OO in the CSS. I mean, I realized that CSS had classes, but it never clicked to me that Class -> Object. It’s like doing what I do now, just saying it’s object oriented instead ;)

    ( Reply )
  20. PG

    Chris M September 16th

    thanks to JW for coming in and straightening some of these points out within the article.

    CSS frameworks should not be used by beginners. things like frameworks and WYSIWYG editors are easier for beginners, but if they are ever going to learn anything, they need to write the code themselves

    ( Reply )
  21. PG

    Brett Jankord September 16th

    A great list of good practices. Using a the star reset is a quick way to help maintain your design across multiple browsers. You could also add an {!– if IE –} stylesheet for any erroneous IE issues that the reset doesnt catch. It’s also easy to add styles for things u do want to keep margins and padding on right after your reset, for example, lists.

    Sorting alphabetically seem like a bit overkill to me yet maybe it would be easier to find things.

    I’ve always indented my text on H1 tags for logos and page headers in which the client wanted a display font. Last I knew, Apple was using a similar method. If you view their base stylesheet and search for -9999px they have header tags with links that are set to -9999px indent. I’m not saying they set web standards, yet it was interesting to know other people use that method. I wish Matt Cutts saw this issue differently.

    OO CSS is completely new to me. I looked through the slideshow and there were some interesting concepts yet it seems like you would need to the right project to implement those ideas.

    As far as multiple stylesheets, I think there a great way to stay organized when working on a project. Just remember to compile them into one stylesheet or as few as possible on launch to reduce HTTP request. Using the @import still counts each stylesheet as a uniqe HTTP request too.

    Thanks for the info. It’s always good to refresh yourself with best practices.

    ( Reply )
  22. PG

    DaveK September 16th

    Not sure about the merits of the Editor tags, it kinda says to me that

    “we filled this space with some article we dont really trust to fill some space”

    why publish it then decry its value using these editor tags.

    if I was new to the site it would make me doubt the validity of the info contained within it.

    ( Reply )
    1. PG

      Jeffrey Way September 16th

      I disagree. There are gray areas when it comes to best practices. It’s helpful to view the opinions of two different people who work in the field…in my opinion.

      ( Reply )
      1. PG

        DaveK September 17th

        I do feel that as this is labeled a beginners guide, maybe conflicting opinions should have been left out, as a beginner in anything I feel that clarity is key, and if you have two conflicting opinions it may cause confusion.

        I fully understand that it represents an opinion from two view points and that neither method is “wrong or right” just a representation of what you might want to do. at times though the editors point does seem to suggest that the authors method is wrong.

        As a beginners article maybe just saying “hey, this is how you can do it, once your comfortable with it there are other options” would have been the way to go.

        Just my point of view.

  23. PG

    Tim Gieseking September 16th

    Good tips. The editor’s notes seem to contradict in some cases, which could be confusing for beginners. But there are gray areas in CSS, so they should probably get used to it, and form their own opinions/practices over time.

    13. Alphabetize your Properties

    As people mentioned above, this is really a matter of preference. I really didn’t like the idea because of things like height/width and margin/padding no longer being next to each other. Then I used it on a few stylesheets and it makes edits much faster. After you get used to it you know exactly where to look for a style. Plus you don’t have to decide where you’d like to list a style, you just put it in ABC order.

    I suppose the same thing could be accomplished by training yourself to always put styles in a certain order, so again, it’s a personal thing.

    However, I do have a question:

    How does this affect speed? I ask because I recently read that ABC order actually IMPROVES rendering speed, yet this article seems to imply the opposite. I haven’t investigated yet whether there’s any truth one way or another.

    Or maybe the editor is referring to speed of writing the code? If that’s the case, then see my opinion above: it actually makes developing a stylesheet faster for me.

    ( Reply )
    1. PG

      Tim Gieseking September 16th

      Also, just to elaborate on the editor’s notes… in some cases the editor’s notes should have replaced the tip, rather than being a footnote. For example – Using multiple style sheets. The editor is correct here. Using multiple style sheets is clean and pretty, but it’s universally known (or should be) that it’s bad for performance. The tip should be “Use One Stylesheet”, with a note that IE-specific style sheets are acceptable if needed.

      ( Reply )
  24. PG

    Chris B September 16th

    Article quality dropped on this one SM. I’m a professional CSS developer and there are at least three of four points here that I would avoid at all costs.

    ( Reply )
    1. PG

      leo rapirap September 16th

      can you please elaborate so we may know what are those points that SHOULD be avoided.

      it will be a big help for us.

      thanks!

      ( Reply )
    2. PG

      Jeffrey Way September 16th

      Professional CSS Developer? Interesting title. Which items do you disagree with?

      ( Reply )
      1. PG

        Ahmad Alfy September 17th

        LOL @ title!

  25. PG

    Rob September 16th

    All in all a nice post, thank you. I appreciate the maybe you’ve been using that for a while and I just haven’t noticed.

    @Chris B. Please elaborate…

    ( Reply )
    1. PG

      Rob September 17th

      Seems the post dropped my attempt to show the editors-note in brackets. That’s what I was referring to with my comment above “I appreciate the editors-notes, maybe you’ve been using that for a while and I just haven’t noticed.”

      ( Reply )
  26. PG

    David September 16th

    Dear editor,

    I don’t care about your opinions. Interrupting an article as you’ve repeatedly done in this post is rude and pointless. No one cares if Glenn’s opinions and practices differ from yours; he’s an independent columnist, let him speak freely. We’re not going to think any less of you or the site if we happen to disagree with Glenn.

    If you insist on distancing yourself for whatever reason, do it at the end of the post or in the comments.

    ( Reply )
    1. PG

      Jeffrey Way September 17th

      Dear David – As I am the editor of this site that provides you with free tutorials, I’ll make that decision. Considering the fact that I created this “Best Practice” series, I think that more than gives me the right to pipe in sporadically – especially when I only really disagreed with two points. Thanks.

      ( Reply )
      1. PG

        DaveK September 17th

        wow what an attitude, not content with belittling your authors, you turn on the people that keep you in business, because lets face it Jeff, you aint doing us any favors by providing us with “free tutorials” there are a squillion sites which do the same quite a few of which are far superior.

        I know one thing for sure I wont be back here in a hurry.

        somebody has a god complex,

      2. PG

        Jeffrey Way September 17th

        Hi David,

        No attitude was intended in my response to you. But seriously – you told me I was “rude and pointless” because I wanted to make sure that the readers got the full story on a couple of points….in a series that I created. That’s not very nice.

      3. PG

        Jeffrey Way September 17th

        But perhaps you didn’t intend for it to be taken that way; and if so, I apologize for the misunderstanding.

      4. PG

        Andy C September 28th

        “I don’t care about your opinions. Interrupting an article as you’ve repeatedly done in this post is rude and pointless”

        Actually David, i think the way you phrased your comment could be considered much ruder than the editors comments which were after all only provided to give an alternative opinion – one which you are free to differ with. I for one found the comments to be helpful and quite valid.

        “you aint doing us any favors by providing us with “free tutorials” there are a squillion sites which do the same quite a few of which are far superior.”

        May i take this opportunity to thank both the author and the editor for a helpful article displayed in a clean and concise way.

        “I know one thing for sure I wont be back here in a hurry.”

        You won’t be missed.

  27. PG

    Jarryd September 16th

    I think an important tip for CSS beginners is CSS Specifity. I only really knew about it fairly recently and has saved my butt on some Suckerfish menus :-)

    ( Reply )
  28. PG

    Yheng September 16th

    I still doubt using HTML 5 Doctype since it is still in experimental stage although I tested with different pages with different Doctypes replacing it with html5’s it validates my page but the nightmare would be on any browsers’ if such time comes they change the way in handling it.

    ( Reply )
    1. PG

      Jeffrey Way September 16th

      I don’t think you need to worry about it. It’s recognized in all modern browsers.

      ( Reply )
  29. PG

    udkl September 16th

    urghh ! Those editors notes spoil the reading flow …. maybe an intrapage link to the editors note that can then be placed just above the comments section could be better.

    ( Reply )
  30. PG

    Sarfraz Ahmed September 16th

    that is great to know, useful info :)

    ( Reply )
  31. PG

    Andrea Austoni September 17th

    This is a good article but I strongly advise against “starting with a framework”. You need to learn CSS first, then use a framework to (maybe) speed things up. Otherwise you will not understand what is going on in your code. Jeffrey Way makes this same exact point when speaking of the 960 grid in this great screencast:

    A Detailed Look at the 960 CSS Framework

    ( Reply )
  32. PG

    erkasoft web tasarim September 17th

    nice article for beginners. I’m using yaml framework. I recommend.

    ( Reply )
  33. PG

    Stephen Webb September 17th

    This is a fantastic article for both beginners and intermediate level developers, as there are many invaluable hints and tricks mentioned here that can save a lot of time and effort. As someone who is still very much learning the basics of CSS I will be keeping this on file and trying to implement as much of it as possible.

    CSS is obviously very powerful, but can become difficult to navigate if you haven’t wrote it out in a set structure as recommended here. It’s interesting to note that by doing this and using further refinements, such as shorthand and combining elements, pages can actually load faster – surely a reason for any developer to put in the extra time and effort. I wasn’t aware of Firebug previously, so will be downloading this shortly to inspect pages and hopefully refine them using these tips!

    ( Reply )
  34. PG

    Designing Studios September 17th

    THaNKs Freind…

    ( Reply )
  35. PG

    Aqib Mushtaq September 17th

    Fantastic article as usual, thanks.

    ( Reply )
  36. PG

    Terri September 17th

    Re: the editor’s note on #29: “Many designers prefer to develop with multiple stylesheets, and then combine them into one file.”

    Build and test with two files and then combine? The clobbered selectors would need to be picked apart with tweezers, no?

    ( Reply )
    1. PG

      Wes September 17th

      You just need to make sure you combine them in the same order that you would load them normally in your webpage so the precedence of the selectors will still be in tact.

      ( Reply )
      1. PG

        Terri September 17th

        Once a separate css file is created for pages with unique styling, it seems inevitably the shared selectors diverge.

        Nice article though.

  37. PG

    Vipul Limbachiya September 17th

    That’s a wonderful article, enjoyed reading and learned lot!! thanks for sharing! :)

    ( Reply )
  38. PG

    Edward September 17th

    Very useful article.
    Thanks

    ( Reply )
  39. PG

    Eric Berry September 17th

    Excellent article! This one is going into my long-term bookmark list.

    ( Reply )
  40. PG

    Jermaine September 17th

    I tried #3 and I have to say it’s good, I don’t know why I didn’t try it before. ps I not a beginner

    ( Reply )
  41. PG

    Steve Davis September 17th

    “19. Hack Less”

    sometimes u cant help it. i reset all my stuff, but i still have to make things work in IE6 and IE7 if the client wants it, and they render things differently. and dont forget IE6 not supporting transparencies in PNGS, or SELECT tags not following the proper z-index stack.

    ( Reply )
  42. PG

    Will Moyer September 17th

    In response to #22, if you’re using a background-image for the logo, where am I supposed to use an ALT tag?

    Should I not use background images for logos and use instead?

    - Will

    ( Reply )
    1. PG

      Brett Jankord September 18th

      I believe Matt says to use an image instead of using background-image. So place your description you might have put in you tag with the background image in the alt tag of the image instead.

      I think SEO wise it helps more to put your logo text in a link inside and h1 tag and use a negative text indent and background image, yet Matt says thats a bad practice. To me an tag H1 has more of an impact on SEO than an image alt tag, but if Google frowns on that method I guess I could use regular images and alt tags.

      ( Reply )
      1. PG

        Kurt Cruse September 23rd

        So would it work best to use an image (with alt tag), inside an anchor, inside an H1 according to Google? Like this?

        {h1}{a}{img alt=Headline text /}{/a}{/h1}

        This way you get the SEO benefit of the H1 and the link, and not the harm of the css indented text? Agree/Disagree?

        (They really should of included a code exmple)

  43. PG

    Web Host Right September 17th

    Thanks for the article, as im still learning about CSS i find it very useful when it can prevent me from getting into bad habits.

    ( Reply )
  44. PG

    libeco September 17th

    Alphabetizing? No, I just make sure I always use the order, for instance, always width and height first and border and margin last.

    And as for 26, the extra selectors, I always use them. They just make life much easier to know which element I’m working on and what it’s parent is. This also saves a lot of time when having to edit something say one year later.

    ( Reply )
  45. PG

    Johannes September 17th

    Great Article even for advanced Developers, which became sloppy with the time.

    ( Reply )
  46. PG

    Abdelwahb September 18th

    THANKS FOR THIS ARTICLE GLEN…ITS USEFUL AND I THINK SOME NEW TIPS HERE NEED MORE UNDERSTANDINGS AND RESEARCHING …
    I ENJOY READING AND RE-READING THX

    ( Reply )
  47. PG

    r_jake September 18th

    Perhaps someone could clear up the #22 issue for me -

    I know that using display:none is a no-go because screen readers don’t pick it up, but is the guy from Google saying that any content hidden using CSS (negative margins or the phark left-indent) isn’t crawled?

    I thought search engine bots just crawled the HTML (one of the reasons for externalising the CSS), but this suggests they parse the CSS too. Is this correct?

    ( Reply )
    1. PG

      Dinu October 12th

      Don’t necessarily believe everything Matt Cutts says. I think he’s just going by what is ‘best practice’, rather than by what the Google bot will actually crawl. I use text with a negative indent so that I can re-style the content for a different device (e.g. mobile) with just the text instead of the logo.

      ( Reply )
  48. PG

    Pete September 18th

    Point 19 – “Hack Less” – should include a recommendation on using conditional stylesheets instead of hacks.

    ( Reply )
  49. PG

    Anmol September 18th

    Nice…Helpful

    ( Reply )
  50. PG

    Nick Brown September 18th

    Anyone else think it’s funny that #10 has an incorrect comment and #11 is how to properly comment?

    ( Reply )
  51. PG

    Alexandros September 19th

    Awesome! Very helpful post!

    Thanks a bunch!!

    ( Reply )
  52. PG

    Dubsak September 19th

    Here’s a link to a tool we built to help speed up your stylesheet work. Kind of a work in progress but…you throw in your HTML and it spits out your selectors. You can try it out here: primercss.com

    ( Reply )
  53. Useful tut, thanks

    ( Reply )
  54. PG

    inlikealion September 20th

    I take issue with this article teaching “Best Practices” to beginners and then using non-semantic class names (like point #8 for example). Don’t teach newbies to label classes=”left right box” etc…

    What happens when a redesign asks you to put the right-hand column on the left, or change the ‘box’ into an inline list? Teach newbies to think about naming/labeling elements based on what they are or mean, not by what they look like in a particular design.

    Someone pointed out earlier in the comments that you might as well be using inline styles if naming things this way, because you’re not separating presentation from content.

    It can seem hard or pointless to think of semantic naming conventions when “left” is so easy, but in the long run you will be much better for it.

    ( Reply )
  55. PG

    Rak September 21st

    Thanks for the great tip, perfect starting place for a beginner

    ( Reply )
  56. PG

    revive September 21st

    Note to the ‘Editor’.. if you are going to ‘edit’ then by all means do so.. but marking up another authors article with comments showing your disagreement, let a lone agreement, is poor Editorial practice. You seem to have a good grasp on CSS, and noted by the number of times you chimed into this article instead of ‘editing’ it.. I think this community would benefit greatly from the same degree of knowledge in Editorial prowess.

    ( Reply )
  57. PG

    brad619rey September 21st

    This is an excellent resource for CSS-addicted designers like me who are just starting out.

    I consistently rely on using CSS to do a lot of my designing and some of the tips, particularly the note on having a reset, were very helpful. Thanks again!

    ( Reply )
  58. PG

    Pseudoclass September 23rd

    Another best practice might be naming your classes and IDs based on their content and not their visual aspects (i.e.; .left to float an item left or .blue to specify a color of a title will make absolutely no sense if the design needs to change in the future).

    ( Reply )
  59. PG

    Satish Gandham September 24th

    Great post, glad to find this early in my carrer.
    I think i shud read it regularly until every point registers in my mind.

    ( Reply )
  60. PG

    Morgan Cheng September 24th

    The tip “16. Use “Margin: 0 auto” to Center Layouts” doesn’t work in IE.

    Is there any solution to center a div in IE?

    ( Reply )
    1. PG

      Jeffrey Way September 24th

      Oh sure it does. :)

      ( Reply )
      1. PG

        Cameron October 3rd

        Ah, you sure? I’m pretty certain that it doesn’t work in IE.

        @Morgan – the usual work around is to use text-align:center on a wrapper element to the elements that you want to center, and then resetting the text alignment (to left) in the centered element.

        As an example, if your html was like this:
        {body}
        {div id=’page’}
        …content…
        {/div}
        {/body}

        and you wanted to center the page div inside the body, your css would look something like this:

        body {text-align: center;}
        #page {
        text-align:left;
        margin: 0 auto; /* obviously one can still set the top/bottom margins
        as needed, so could be margin:30px auto 10px auto;
        for a 30px top margin and a 10px bottom margin */
        width:800px; /*or whatever the width is – can be %, em, etc */
        }

      2. PG

        paul October 4th

        It doesn’t work in IE5, hence the text-align fix was born (and admittedly put to bed with other IE5 support.

  61. PG

    muthiulhaq September 24th

    nice! thank you

    ( Reply )
  62. PG

    Ricardo September 28th

    Excellent post. I also dislike the editor´s notes inserted in the post. It makes it seem like a rough draft. I think the editor and author should work out their different opinions so that the final post takes in account the editor´s input.
    Just my two cents. Both the author and the editor make valid points.

    ( Reply )
  63. PG

    neel September 30th

    Nice Article… with all the aspects of the CSS

    ( Reply )
  64. PG

    h2spot.net October 9th

    very nice tutorial… thanx

    ( Reply )
  65. PG

    Joe October 11th

    Just realised that my CSS is a bit messy :P

    ( Reply )
  66. PG

    Greg October 12th

    Holy Jumpin’… too many editors’ notes. The editor and writer should have a dialogue BEFORE publication, not after. Not sure which of the two made the decision to do it with inline comments, but it’s distracting and undermines the authority of the article, which is good for neither party.

    ( Reply )
  67. PG

    Joel October 14th

    I disagree with the editor’s note on #27. Of course we want to reset default padding and margins. The only reason that elements have padding or margins in the first place is because the designer specifies it. And * doesn’t override specific classes, at least in the case of margin and padding. (Although IIRC it does for most text-related stuff).

    ( Reply )
  68. PG

    iLinx October 18th

    Nice :]

    ( Reply )
  69. PG

    ROBIN October 26th

    verry verry helpfull.. thnx a million..

    ( Reply )
  70. PG

    tutorial blog October 28th

    thank for tutorial.

    ( Reply )
  71. PG

    kongski November 1st

    i love it., really.. thanks a lot.

    ( Reply )
  72. PG

    Evan November 17th

    I can’t agree more with many of the points mentioned in the article.

    On the topic of writing clean CSS, it really can’t be stressed enough that if you have a ’style guide’ for CSS document structure, you’ll save a big headache later if you have to open the file in a month or two. For example, even something as simple as putting positioning (position, padding, margin, display, float) ahead of other items like font and background means you’ll know where to look, at a glance, in any one of your CSS files.

    Thx!

    ( Reply )
  1. Arrow
    Gravatar

    Your Name
    November 17th