Why is this page text-only?

Quick Tip: Applying multiple classes

This is quick and simple tip but I know a bunch of people who weren't aware of it so I felt it warranted a post. We all know that CSS classes are a great way of applying a specific style or position to an element. However not a lot of people know that you can apply more than one class to an element. I've seen many people have styles like this:

.indent { padding-left: 25px; }
.highlight { background-color: #ffff00; }
.highlightindent { background-color: #ffff00; padding-left: 25px; }

While there isn't anything wrong with that third style, it isn't neccessary. You can apply both the indent style and the highlight style to the same element, just separate them with a space, like this:
<p class="highlight indent">This text is highlighted and indented</p>

Click here to see a demo

1 element. 2 classes. That's all there is to it. If you have a quick tip you'd like to see on Code Scene, send it to jay@codescene.com

Del.icio.us Digg Yahoo! My Web Seed Newsvine reddit Technorati Facebook StumbleUpon Mark in ma.gnolia Google Bookmarks Windows Live

TrackBacks

TrackBack URL for this entry:
http://www.codescene.com/cgi-bin/mt/mt-t.cgi/52

2 Comments

Since the topic is multiple classes I thought I might chime in with a related IE bug which I ran into after reading this article. Building off your example, lets say that a developer wanted to add a third style such that anything that was both indented and highlighted was also italicized.

This CSS might look like: .indented.highlighted { text-style:italic; }

This however, will not work on IE5-6. IE will instead ignore the first class, <span class="code">.indented</span >, and read the selector as just the second class, <span class="code">.highlighted</span>. Therefore, IE will apply this new rule to anything tagged as <span class="code">class="highlighted"</span>.

Hey Jeff...
I think you misread the article. The CSS classes don't get jammed together in the code. They remain completely seperate. You simply add multiple entries to the class attribute on the html end of things.


So, the additional CSS would actually look like:
.italicized { font-style:italic; }

you'd then add the third class to the list:

<p class="highlight indent italicized">

I'm on a mac so I can't test this on ie from here, but that should work fine.

Leave a comment