tags:

views:

162

answers:

3

I want to target an HTML element when BOTH the id and class selectors match.

Ie, if the fieldset has id 'id1' AND class 'collapsed', some CSS rule applies (to ensure its height is reduced to zero).

CSS 2.1 docs suggest that multiple attribute selectors may fill this task:

http://www.w3.org/TR/CSS2/selector.html#matching-attrs

But the following syntax doesn't seem to take effect (tested in Safari and FFox3):

div[id=id1][class=collapsed] { display: none ; }

Is there a way to do something like this?

div#id1.collapsed { /* rules */ }
+4  A: 

You are doing it right, but the order of the selectors is wrong, you need to put the element first, then the class, and then the id

div.myclass#myid { /*rules*/ }

IMPORTANT EDIT:

div#myid.myclass { /*rules*/ }

Also works.

krusty.ar
Great info. Do you have a reference from the spec? I just can't find it.
Bobby Jack
krusty.ar
@Bobby Jack, I misread your question, I can't find anywhere that this order is the only valid one, I just assumed it because I always use it and the op supposedly didn't work, but then I tested it and div#myid.myclass works perfectly.
krusty.ar
+1  A: 

You want div.myclass#myid { /*rules*/ }, but with one caveat: this won't work in IE (as always)

See http://css-discuss.incutio.com/?page=InternetExplorerWinBugs (specifically the Multiple ID class bug which is discussed at http://archivist.incutio.com/viewlist/css-discuss/60941)

DarkWulf
A: 

Thanks Krusty! And thanks also DarkWulf for the warning about IE :)

Btw, I discovered that I had slightly wrong syntax for the approach I was trying.

The correct code for what I was trying (multiple attribute selectors) would have been

div[id="id1"][class~="collapsed"] { /* */ }

The tilde means that div[class~="collapsed] will match with the same rule that div.collapsed would, ie against any of the classes specified.

div[class="collapsed"] { }

matches the class attribute exactly, so it will match

<div class="collapsed"></div>

and won't match

<div class="collapsible collapsed"></div>
Chris Burgess