Aaron Saray

open source programmer,
web developer

entrepreneur, author
and musician

My Blog

contains PHP, Web and business/entrepreneurial related content. Please join in the conversation!

Name CSS Classes More Descriptive

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.

This entry was posted in CSS, Misc Web Design and tagged , . Bookmark the permalink.

2 Responses to Name CSS Classes More Descriptive

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

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>