Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS selector for an element having class .a and class .b

I need to style an element that has both class .a and class .b. How do I do it?

The order the classes appear in the HTML might vary.

<style>     div.a ? div.b {         color:#f00;     } </style> <div class="a">text not red</div> <div class="b">text not red</div> <div class="a b">red text</div> <div class="b a">red text</div> 
like image 409
Raanan Avidor Avatar asked Apr 30 '09 15:04

Raanan Avidor


People also ask

How do you select a class and element in CSS?

To select elements with a specific class, write a period (.) character, followed by the name of the class. You can also specify that only specific HTML elements should be affected by a class.

Can a CSS element have two classes?

An element is usually only assigned one class. The corresponding CSS for that particular class defines the appearance properties for that class. However, we can also assign multiple classes to the same element in CSS. In some cases, assigning multiple classes makes page styling easier and much more flexible.

Can class selector have multiple classes?

class selector can also be used to select multiple classes.


2 Answers

That's entirely possible. If you specify two classes on an element (without any spaces), that means that it must have both for the rule to apply.

div.a {    color: blue;  }  div.b {    color: green;  }  div.a.b {    color: red;  }
<div class="a">    A  </div>  <div class="b">    B  </div>  <div class="a b">    AB  </div>
like image 104
bdukes Avatar answered Sep 26 '22 00:09

bdukes


Class selectors can be combined:

div.a.b {   color: red; } 

Quoting from the spec:

To match a subset of "class" values, each value must be preceded by a ".".

For example, the following rule matches any P element whose "class" attribute has been assigned a list of space-separated values that includes "pastoral" and "marine":

p.marine.pastoral { color: green } 

This rule matches when class="pastoral blue aqua marine" but does not match for class="pastoral blue".

like image 42
Rob Kennedy Avatar answered Sep 25 '22 00:09

Rob Kennedy