Advertisement
Advertisement


How to combine class and ID in CSS selector?


Question

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>
2016/07/10
1
229
7/10/2016 12:16:42 AM

Accepted Answer

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

Edit, 4 years later: Since this is super old and people keep finding it: don't use the tagNames in your selectors. #content.myClass is faster than div#content.myClass because the tagName adds a filtering step that you don't need. Use tagNames in selectors only where you must!

2014/05/07
336
5/7/2014 8:16:55 PM

There are differences between #header .callout and #header.callout in css.

Here is the "plain English" of #header .callout:
Select all elements with the class name callout that are descendants of the element with an ID of header.

And #header.callout means:
Select the element which has an ID of header and also a class name of callout.

You can read more here css tricks

2018/06/28

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?

2009/06/22

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 {
    /* ... */
}
2009/06/22

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.

2009/06/22

use: tag.id ; tag#classin the tag variables in your css.

2016/08/31

Source: https://stackoverflow.com/questions/1028248
Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]