Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS Selector that applies to elements with two classes

Is there a way to select an element with CSS based on the value of the class attribute being set to two specific classes. For example, let's say I have 3 divs:

<div class="foo">Hello Foo</div> <div class="foo bar">Hello World</div> <div class="bar">Hello Bar</div> 

What CSS could I write to select ONLY the second element in the list, based on the fact that it is a member of both the foo AND bar classes?

like image 693
Adam Avatar asked Sep 22 '10 18:09

Adam


People also ask

Can an element have 2 CSS classes?

To specify multiple classes, separate the class names with a space, e.g. <span class="left important">. This allows you to combine several CSS classes for one HTML element.

How do you select an element with multiple classes?

Use the getElementsByClassName method to get elements by multiple class names, e.g. document. getElementsByClassName('box green') . The method returns an array-like object containing all the elements that have all of the given class names.

Can you assign two classes to an element?

HTML elements can be assigned multiple classes by listing the classes in the class attribute, with a blank space to separate them.


1 Answers

Chain both class selectors (without a space in between):

.foo.bar {     /* Styles for element(s) with foo AND bar classes */ } 

If you still have to deal with ancient browsers like IE6, be aware that it doesn't read chained class selectors correctly: it'll only read the last class selector (.bar in this case) instead, regardless of what other classes you list.

To illustrate how other browsers and IE6 interpret this, consider this CSS:

* {     color: black; }  .foo.bar {     color: red; } 

Output on supported browsers is:

<div class="foo">Hello Foo</div>       <!-- Not selected, black text [1] --> <div class="foo bar">Hello World</div> <!-- Selected, red text [2] --> <div class="bar">Hello Bar</div>       <!-- Not selected, black text [3] --> 

Output on IE6 is:

<div class="foo">Hello Foo</div>       <!-- Not selected, black text [1] --> <div class="foo bar">Hello World</div> <!-- Selected, red text [2] --> <div class="bar">Hello Bar</div>       <!-- Selected, red text [2] --> 

Footnotes:

  • Supported browsers:
    1. Not selected as this element only has class foo.
    2. Selected as this element has both classes foo and bar.
    3. Not selected as this element only has class bar.

  • IE6:
    1. Not selected as this element doesn't have class bar.
    2. Selected as this element has class bar, regardless of any other classes listed.
like image 98
BoltClock Avatar answered Nov 05 '22 00:11

BoltClock