arb
arb

Reputation: 7863

Add CSS Class by Selector

I hope this isn't a duplicate, but I'm not sure even how to phrase what I'm trying to do. I have some utility CSS rules for like clearing floats and creating horizontal boxes. What I want to do is something like this:

.clear{
    clear:both;
}
#someID > div{
    /*apply the .clear class here*/
}

I know I can do this with JavaScript, but I would like to avoid having class="clear" a million times if I can avoid it. I would also like to avoid duplicating the style information in the second selector so I don't have to maintain multiple utility classes.

The .clear class is just an example, my actual classes are more involved.

Upvotes: 10

Views: 7769

Answers (3)

Viruzzo
Viruzzo

Reputation: 3025

You can't do it in pure CSS. You can do it easily with LESS or jQuery, just use: $('#someID > div').addClass('clear');.

Upvotes: 1

Benjamin Crouzier
Benjamin Crouzier

Reputation: 41865

In HTML/CSS, you can have multiple clases like this:

HTML

<!--If you are using a id and a class:-->
<div id="someID" class="clear"></div>

<!--If you are using 2 classes-->
<div class="someClass clear"></div>

CSS

.clear{
    clear:both;
}
#someID {
    /* specific style here */
}
.someClass {
    /* specific style here */
}

Upvotes: -1

wsanville
wsanville

Reputation: 37516

Really, you're just going to have to use your utility classes like clear throughout your markup, unless you want to do something like this (which is probably not what you want):

.clear, #someID > div 
{
    clear:both;
    /* this assumes you have no other rules here, which probably isn't true */
}

In short, there's not much better you can do, unless you want to use a preprocessor for your CSS, like LESS.

Upvotes: 6

Related Questions