Save Time By Using Multiple Classes

Quick Tip: Save Time by Using Multiple Classes

Tutorial Details
  • Difficulty: Beginner
  • Completion Time: 5 Minutes

One of the most exhausting aspects of web development is writing out endless amounts of CSS styling for various elements – that differ only slightly in style from one another. It has taken the life (or will) of many a talented designer. Well, why give each element its own unique CSS entry, when you can mix match and add re-usable CSS styling to elements using multiple CSS classes?

Step 1: Set Up The CSS

Lets start with identifying and writing out some of our most common CSS markup. We’ll set them up as individual styles. The ones that we’ve set up here are the most basic, but the same technique can be applied to even the coolest CSS 3 properties.

.primaryColor {
color: blue;
}

.articleImage {
border: 1px solid #292929;
padding: 5px;
}

.standOut {
font-size: 22px;
}

.important {
font-weight: bold;
}

.floatRight {
float: right;
}

Step 2: Applying The Classes In Our Document

  • <p class=”primaryColor important”>This text will be blue and bold</p>
  • <img src=”#” class=”articleImage floatRight”>This image will be floated to the right, and will have some padding and a border.</p>
  • <p class=”standOut”>This text will be huge</p>
  • <p class=”primaryColor standOut important”>This text will be blue, 22px large, and bold. </p>

Why It’s Useful

This can be a massive help, especially when designing layouts… you can use one class to define the size and width, and another class to define the positioning. Hope this helped!

Editor’s Note: Keep in mind that, in some of the older browsers – meaning older than IE 6 – this “multiple classes” method will fail. What are your thoughts on this approach? P.S. Have a killer quick tip? Email us and we’ll talk.

Tags: tips
Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • Clayton Ferris

    Applying multiple classes is a great practice, however that is a terrible example. Class names should be representative of your content not the style of your content. What happens when you redesign your site in a few months, or just decide to change color schemes? Your .blue class is totally useless.

  • Roc

    Yay First :D

  • http://corrgraphics.net John

    Good Tip, I rarely use classes to the extent I should

  • http://www.detacheddesigns.com Jeffrey Way

    @Clayton – Absolutely. Very good point. It may not seem like a big issue at first – but you’ll definitely have some problems down the line.

  • http://enhance.qd-creative.co.uk James

    A nicely written little tip, thanks! :)

    This does raise the question of whether it’s okay to sacrifice semantics for convenience. Giving an element a single and meaningful class/ID and applying all styles to that is a much more semantic approach. However, there is the risk of bloated and unnecessary code with the semantic approach plus it would probably be less maintainable than using multiple classes as you’re suggesting. But then using multiple classes may have the same bloated result because of all the classes you’d have to add to each element. And then it would also be hard to maintain! – For example, if you wanted to change the size of all your “size22″ (i.e. class=”size22″) elements you’d have to go through every element and rename the class correspondingly!!

    So, I suppose the whole thing is still up for discussion. Anyone who reads this should consider this though – Is it better to name a class according to it’s purpose (e.g. class=”warning”) or according to it’s style attributes (e.g. class=”red”)?

    Plus there is the whole issue of backward compatibility / cross-browser support!

  • http://www.detacheddesigns.com Jeffrey Way

    @James – Yeah – people split on this concept. I tend to stick more with naming according to its “purpose”. Although, I’ve definitely done both. Cross-browser support is fairly widespread…except for very, very old browsers.

  • http://dev.sgdg.net Stan Grabowski

    Good advice. One quick question though. Why would you use a class name with a color or some other visual term? If your client or boss comes back and asks you to change things from blue to orange, you then have to change your class names AND your CSS file.

    Class names (and IDs) should relate to what they are marking up, not to how it will look. Something like is an example of how classes should be named.

  • http://css-tricks.com Chris Coyier

    I agree that the theory here is good but the actual example is problematic. You’ll make thing easier on yourself and the lifespan of your site if you avoid names like “blue” and “bold” and make them describe what you are trying to accomplish instead like “callout” or “button”.

  • http://www.prestigebulletin.com Jonathan

    What are your thoughts on this approach?

    I know longer design for anything older than IE 6. If car companies no longer support their vehicles after 10years ( VW ) why must we support outdated browsers. Besides, the number of users of IE 5 and below are in the single digit %. So why bother.

    I have been playing with classes as of late, at it really opens up doors of possibilities. For example – created a function the outputs a post class( post1 Y2008 M08 D15 protected authorname category-xyz etc)
    Now if I want assign a color to different authors, no problem, or year, or month.

    NBThing to remember here is that the styles (classes) are applied in a cascading manner, so you have to be careful in duplicating the styles. For example, if you set the width for CSS class XY, it will override the one set in the class YZ.

  • http://sas171.net sas171

    Yeah, style=”width: 100px; float: right;” is even shorter, isn’t it? You don’t have to define all the silly classes in the extern CSS file!

    Seriously, we use CSS to get one abstraction layer more and distinguish between content (XHTML) and presentation (CSS). Using your advice people will bring the presentation layer information back into content layer.

    The CSS classes should reflect the logical nature of the element. E.g.: hint, comment, category-name, post-excerpt. However the last one could be written as … … … . In this case you are able to change the look of the elements when required without touching the XHTML and your XHTML will be much cleaner.

    Cheers.

  • http://www.ryanimel.com Ryan Imel

    I second everyone’s remarks about this being an excellent tip but a poor example. We shouldn’t be instructing people to add classes based on the visual outcome under any circumstances.

    Also, for anyone who uses WordPress that likes the idea of elements being packed with semantic classy goodness, check out Sandbox, a theme for those who build themes. Trust me, it’s overflowing with developer happiness: http://www.plaintxt.org/themes/sandbox/

  • http://blog.shofr.com shofr

    I agree with Clayton. Anyone that sent me CSS marked up like this wouldn’t get much respect from me. This method is short sighted and borders on counter intuitive.

  • http://www.detacheddesigns.com Jeffrey Way

    Everyone – It was my initial intention to leave the class names relating to the style in – out of courtesy to the author. Plus, I thought it would make for an interesting debate. However, considering the fact that many new developers will be learning from this, I’ve edited the names to something that I’m more comfortable with.

    Although “.center” refers to the styling, I think this is okay…But that can definitely be debated. I suppose it all comes down to how semantic you want to be!

    Keep the comments coming. This is an important subject.

  • http://enhance.qd-creative.co.uk James

    Yeh, good idea Jeffrey. Like you said, a lot of people use this as a learning resource – we don’t want them getting the wrong idea…

  • http://www.prestigebulletin.com Jonathan

    I second James. Good Idea Jeffrey, as for center I use ac = align center ; al = align right ; ar = align left ; fr = float right ; fl = float left and one more fix = more in depth clear:both

    Not the best way, but works for me.

  • m0nkie

    my example:
    imagine, i need unordered list of items with bullets coloured differently for each item. my bullet will be 6 by pixels image. i’ll have 5 items. so i create image 6 by 30 pixels containing blue, orange, gray, green and pink bullet. then for the 1st bullet i assign background-image, and then for others i change its position using my classes..

    html:

    list item #1
    list item #2
    list item #3
    list item #4
    list item #5

    css:

    li .dot {
    position : absolute;
    top : 0.4em;
    z-index : 1;
    width : 6px;
    height : 6px;
    margin-left : -15px;
    background : url(fo-list.png) no-repeat;
    }

    .orange {
    background-position : 0 -6px;
    }

    .gray {
    background-position : 0 -12px;
    }
    .green {
    background-position : 0 -18px;
    }
    .pink {
    background-position : 0 -24px;
    }

  • m0nkie

    oops…
    here is disappeared html:

  • http://talkingtofu2.iblogger.org Taylor Satula

    Ive been deving a css file that does rbg align font etc. so this will be helpful

  • http://thesacrificebunt.com Melvin Nieves

    Love the css tips, thanks!

  • http://www.ben-griffiths.com Ben Griffiths

    Personally I have never been a fan of doubling up classes on a single element – the risk is to high for me to brake something without realizing it when modifying one of the classes. I prefer instead to create a new single class to handle the difference, eg:

    .image {
    border: 1px solid #000;
    }

    .image-right {
    border: 1px solid #000;
    float: right;
    }

    For me this gives much more control. It may make the CSS larger, and slightly more complicated, but safety of editing rules over this for me.

  • Medium

    Nice tip, keep them comming :)

  • http://dmasq.blogspot.com Dan

    Good idea naming them .primaryColor .secondaryColor instead of what I see people doing (e.g. .blueColor etc…). My advice is to make sure you really need multiple classes for what you’re doing before you actually use more than one. Keeping layout and style as separate as possible is key when it comes to easily maintaining websites.

    ah woops, you have a typo posted as of 8/13 3:34pm:

    .floatRight {
    float: rightright;
    }

    nice post idea! keep them coming!

  • http://www.solutiondesigns.net Philo

    Great Tip! :)

  • http://craigsnedeker.blogspot.com/ Craigsnedeker

    Awesome tip, I never knew you could do that!

  • http://www.1pixelbrush.com Dan

    These tips are getting some traffic eh, nice, keep em coming

  • http://davetufts.com Dave Tufts

    Taking what Dan said even farther, it’s important the CSS definitions don’t describe how something looks right now, but rather what it is.

    “floatRight” describes how it looks. The whole purpose of an external CSS is that you can deal with layout issues separately. With .floatRight, if your layout changes and you want the image on the left, you have to change the CSS and the HTML. Instead, what is the image? Describe the content:

    img.headshot { float: right; }
    img.primary {float: right; }

    Also, to comment on what Ben said, you should never need .image { } or .image-right { }. Instead don’t use any class:

    .article image {
    border: 1px solid #000;
    }
    .article image.primary {
    border: 1px solid #000;
    float: right;
    }

  • http://www.insicdesigns.info insic

    i started to like this quick tips. keep it up nettuts!

  • http://www.freshclickmedia.com Shane

    Well – this article has certainly provoked a lot of debate, which is a good thing.

    There are different levels of semantics with CSS – I’d never use .blue, for example, because, as many people have said, your .blue class might not have blue characteristics further down the line.

    I prefer to use semantic terms such as header, footer and sidebar. But… I have mixed things up a little by using multiple classes.

    In his book ‘Transcending CSS’, Andy Clarke suggests that for layout, sites use a similar convention, such as header, footer and so on. That way, the layout ‘blocks’ are consistent across sites, and a user-defined stylesheet could style them in a similar way.

  • http://www.mongoink.com Jason

    I agree with Clayton, to a point. although the class can be described according to its content this does not mean it has to. The content can change, but the element that contains it should stay the same. But in saying that, thats the whole beauty of CSS. Giving the user to be ability to tag into the script and name sections as they see fit. Ok semantics can and probably does play a big part in all this, but it is not required, and at the end of the day this tut is only an example of the functionality that a class has. To be able to use a single css rule over and over on a page.

    Not the best Tut, but the thought behind it is correct.

  • http://manuelressel.com Manuel

    I always used a floatRight-class but never thought about a primaryColor-class or an important-class. Nice idea!

  • Kim Dolleris

    What Insic said :)

  • http://none ben

    very nice trick,thanks

  • http://www.kieru.com Rob

    I don’t know why everyone is ganging up on you for your CSS class names. The benefit between generic titles designed to convey the overall effect, versus something more specific is pretty negligible. On the one hand, if your name expressly defines what the class is to do… it makes it a hell of a lot easier to see what’s going on in your code. On the other hand, generic names that convey a more vague approach offer you the flexibility of altering the specifics (ie. blue to yellow, 21pt to 25pt, etc) without muddying up the waters with a class name that suggests something radically different.

    But then… look at .standOut. If you saw <div class=”standOut”> you wouldn’t know immediately if that class had a bolding effect, increased the font size, doubled the margins, italicized it… etc. ‘standOut” could encompass any of all of those, making the choice between generic and explicit largely a matter of taste in my opinion.

    Regarding the tip though; I think it’s absolutely brilliant. I remember when I first learned you could specify multiple styles I went looking through other sites code and wondering ‘why the hell aren’t people USING this’. I find it’s great for when I have two blocks with many of the same styling, but then one or two things that are different (like maybe ‘A’ has green text and ‘B’ has blue).

    As for browsers lower than IE6… no worries. If you’re still coding for browsers lower than IE6 well, kudos to you and all… but I would ask why. If your client cannot function without that 0.3% market then most likely he needs to upgrade his OWN system.

  • http://www.fricks.com.br fricks

    Good tip!
    Thank you :)

  • Brian

    Isn’t it best ot keep the markup XHTML elements such as etc as class free as possible and target all of it from the CSS file so changes in future can be done from the CSS file and the markup does not need to be touched.

  • http://jasonwilsondesign.com Jason

    @Rob, the stand out class doesn’t need to convey that it deals with bolding. The idea behind this class is, if you decide you want to change the way your elements can stand out you can do it once in the css without having to change it a hundred times in the CSS.

    For example: Client brief says first paragraph must stand out. You present them with the results of this css.

    .standOut {
    font-size: 22pt;
    font-weight: bold;
    }

    When you present the complete beta site to the client, client asks if something else could be done to make it stand out more. You respond with:

    .standOut {
    font-size: 22pt;
    font-weight: bold;
    background-color: #999999;
    border: 1px solid #666666;
    }

    If you had been using a class name like ‘.bold22′ you’d be in for a fun few hours of find and replace.

    The idea is to make it so the function is clear not the style.

  • http://dinolatoga.com Dino

    I think there’s a typo sir:

    .floatRight
    {
    float: rightright; <– wrong, wrong…
    }

  • http://ha.xors.org Braden Keith

    very quick and useful, thank you. I don’t usually think of adding multiple classes to an object like that

  • Wayne

    @Ben — Yes, that’s the approach I take. There may be some redundancy, but it allows me to keep things straight, and I worry less when I need to tweak a class.

  • Ann

    I am super lazy about making classes, but I always spending more time adding style to individual paragraphs. I really need to start doing this more often.

  • Cameron

    This is a great tip. I’ll be sure to use it.

    Thanks!

  • http://laminbarrow.com Lamin Barrow

    You code markup wont be valid XHTMl if you go down the path of using multiple classes on an element.

  • http://www.thelastknight.co.uk Jammin

    Good tips but word up to Dave Tufts tip!

  • http://www.easilyamusedinc.com James Tryon

    This is one of those things that you know about but you never practice. Meaning its a great tip but you just dont think about it when you could be using it.

    Thanks for the wake up, also i got what you where saying. there is no need to pick it apart that much.
    Thanks for you help.

  • Pingback: “Multiple Classes” in CSS ??

  • http://www.sharemation.com/ramil18/mysite/home.html harem

    hi Insic!

  • http://www.workhabit.com/ Jonathan

    This article leaves something to be desired, but it’s a great idea.

    You’re using named elements, rather and descriptive elements.

    What css is trying to emulate is something called a polymorphic function, or polymorphism. Code should be written without a specific type, so that you can re-use that code down the road on all kinds of things you may not have originally intended. So, for example, instead of calling your image callouts .articleImage, consider something like .decoratorstyle1. There are a ton of naming conventions, and that’s NOT THE POINT of this. If you use abstraction, you can re-use your base classes outside of their intended name space and object space, and dramatically reduce the amount of css required, especially on complex or multi-layout sites. Remember, a subclass should only have to capture the delta of the change from the parent class, which really eliminates a lot of code.

    See this article on the subject:
    http://www.simplebits.com/notebook/2003/04/15/css_inheritance.html

  • Jatin Meshiya

    I am Yahoo Store Developer, and I always use the CSS classes that repeat again and again. in fact if you have ever find e-Commerce layout has category page, product listing pages, home page with future products and many more… such as new arrivals in left navigation, highest rated product in right navigation etc has same block layout. In these cases we are using the same style. My mean to say one same class.

    We also maintain hierarchy in CSS. It is really very good practice in e-Commerce layout. One more thing I want to tell you that if possible then use the name that indicate the proper place that they will be apply.

  • http://www.novolume.co.uk Dave Ellis

    This is really useful and something that I need to work on implementing more into my sites. I think a lot of being able to write your css out like this comes down to planning.

  • srawetek

    very,very goodtip.