tags:

views:

1227

answers:

6

If I have the following div

<div class="sectionA" id="content">
Lorem Ipsum...
</div>

Is there a way to define a style that expresses the idea "A div with id='content' AND class='myClass'"?

Or do you have simply go one way or the other as in

<div class="content-sectionA">
Lorem Ipsum...
</div>

or

<div id="content-sectionA">
Lorem Ipsum...
</div>
+9  A: 

In your stylesheet:

div#content.myClass

Edit: These might help, too:

div#content.myClass.aSecondClass.aThirdClass /* Won't work in IE6, but valid */
div.firstClass.secondClass /* ditto */

and, per your example:

div#content.sectionA
ajm
A: 

Ids are supposed to be unique document wide, so you shouldn't have to select based on both. You can assign an element multiple classes though with class="class1 class2"

Ben Hughes
The class can change. Per example, you can have div#id.active and div#id.inactive.
Daniel Moura
fair enough, come to think of it, I have used this functionality, but I misunderstood what the desired behavior was.
Ben Hughes
A: 

.sectionA[id='content'] { color : red; }

Won't work when the doctype is html 4.01 though...

A: 

You can combine ID and Class in CSS, but IDs are intended to be unique, so adding a class to a CSS selector would over-qualify it.

Eric Wendelin
That's a good point. I'm thinking if maybe you have a set of very general classes (setting things like float, height/width, maybe things like font) and you'd like to override something in them in this unique exception?
ajm
Unless you use the same stylesheet with different pages. :-)
Patrick McElhaney
Another example: when classes are added dynamically with Javascript (#optionalFields.enabled)
Patrick McElhaney
Even if you use the same stylesheet with different pages, it'd really be better to put a class on the body or have one style for the ID and then separate class definitions for the classes with the appropriate overriding styles.
Eric Wendelin
A: 

Well generally you shouldn't need to classify an element specified by id, because id is always unique, but if you really need to, the following should work:

div#content.sectionA {
    /* ... */
}
Blixt
A: 

There's nothing wrong with combining an id and a class on one element, but you shouldn't need to identify it by both for one rule. If you really want to you can do:

#content.sectionA{some rules}

You don't need the div in front of the ID as others have suggested.

In general, CSS rules specific to that element should be set with the ID, and those are going to carry a greater weight than those of just the class. Rules specified by the class would be properties that apply to multiple items that you don't want to change in multiple places anytime you need to adjust.

That boils down to this:

 .sectionA{some general rules here}
 #content{specific rules, and overrides for things in .sectionA}

Make sense?

Gabriel Hurley