0

Is there a way to apply a style to elements that contain multiple classes?

Example


<div class="foo"     > foo     </div>
<div class="foo bar" > foo bar </div>
<div class="bar"     > bar     </div>

I only want to modify the styling of the element that contains class "foo bar". The XPath information would be something like //div[contains(@class,"foo") and contains(@class,"bar")]. Any ideas for pure CSS, w/o having to create a unique class?

Community
  • 1
  • 1
vol7ron
  • 40,809
  • 21
  • 119
  • 172

2 Answers2

5

Like this:

.foo { background: red; }
.bar { background: blue; }
.foo.bar { background: purple; }
aorcsik
  • 15,271
  • 5
  • 39
  • 49
  • 2
    If only it would KNOW that red and blue make purple - it could do this automagically! ;) – Dave Jun 10 '11 at 16:06
  • Probably not worth mentioning, but just in case, IE6 has some issues with this. @BoltClock explains it well here: http://stackoverflow.com/questions/3772290/css-selector-that-applies-to-elements-with-two-classes/3772305#3772305 – thirtydot Jun 10 '11 at 16:06
  • In IE6: `e.c1.c2...cn` = `e.cn` where `e` is an element and `ci` is a class with position `i`. – melhosseiny Jun 10 '11 at 16:10
  • @thirtydot: If I had seen that question I probably wouldn't have wasted my time asking :) --- and I did search SO and google :) -- could you check on attribute selectors in IE6 – vol7ron Jun 10 '11 at 16:14
  • @vol7ron: IE6 simply does not support attribute selectors, like those in your answer. – thirtydot Jun 10 '11 at 16:18
  • @thirtydot: I figured :-/, fortunately IE6 is almost 4 versions in the past and, really, no longer has to be supported; much like IE5.5 is no longer supported. – vol7ron Jun 10 '11 at 22:15
1

Solutions


  1.  .foo.bar { ... }
    
  2.  [class="foo bar"] { ... }             // explicit class name
    
  3.  [class~="foo"][class~="bar"] { ... }  // inclusive class name
    
Community
  • 1
  • 1
vol7ron
  • 40,809
  • 21
  • 119
  • 172