Name CSS Classes More Descriptive

October 30th, 2008 by Aaron

Get MS hosting starting at less than $2 month + free domains.Click Here Now to Save.

One thing I remember being pounded into my head is to not create CSS classes after their physical attributes. So, for example, if your error text is red, do not call the class red. Instead, be more descriptive of the content.

BAD!

1
.red { color: red }
1
<span class="red">There was an error!</span>

Instead, I was always encouraged to give the class something more descriptive, such as ‘error’.

GOOD!

1
.error { color: red; }
1
<span class="error">There was an error!</span>

Well, that seems pretty cut-n-dry for a simple example like that. However, in my most recent design, I’ve come across some more complex situations. For example, when you’re visiting the webpage, the background of an element might be a really dark grey. When you’re an authenticated user, however, I need it to be a medium grey (hey don’t ask - just wait for WhereIsTheBand.com to be done!).

Of course, during design, I went to the dark side right away:

BAD!

1
2
.darkGrey { color: #101011 }
.mediumGrey { color: #212122 }

Now, I know I should come up with some descriptive name, perhaps something like “userLoggedIn” or something, but I plan on using these classes in different areas as well. They might not be dependent on the user being logged in - just might look better that way. I didn’t want to make a lot of duplicate CSS code either.

The compromise: be semi descriptive.

COMPROMISE!

1
2
.lowContrastBackground { color: #101011 }
.mediumContractBackground { color: #212122 }

Not perfect, but seems like a better alternative.

Tags: ,


2 Responses to “Name CSS Classes More Descriptive”

  1. James Rodenkirch Says:

    Another option would be to use the cascading part of CSS to your advantage. You could define a class, for lack of a better name right now lets call it ‘contrast’:

    .contrast { color: #101011 }
    .authenticated .contrast { color: #212122 }

    Then, when the user is authenticated, just wrap your area that changes with another element that has a css class of ‘authenticated’.

    Example:

    [ input type='text' class='myElement' ]
    [ span class='authenticated' ][ input type='text' class='myElement'][/span]

  2. James Rodenkirch Says:

    grrr, typos in my last post

    Example:

    [ input type='text' class='contrast' ]
    [ span class='authenticated' ][ input type='text' class='contrast'][/span]

    sorry

Leave a Reply

©2008 102 Degrees LLC - All Rights Reserved Home Services Products Network Blog Open Source Learning Contact