Web/CSS/Class selectors

From Get docs


The CSS class selector matches elements based on the contents of their class attribute.

/* All elements with class="spacious" */
.spacious {
  margin: 2em;
}

/* All <li> elements with class="spacious" */
li.spacious {
  margin: 2em;
}

/* All <li> elements with a class list that includes both "spacious" and "elegant" */
/* For example, class="elegant retro spacious" */
li.spacious.elegant {
  margin: 2em;
}

Syntax

.class_name { style properties }

Note that this is equivalent to the following attribute selector:

[class~=class_name] { style properties }

Examples

CSS

.red {
  color: #f33;
}

.yellow-bg {
  background: #ffa;
}

.fancy {
  font-weight: bold;
  text-shadow: 4px 4px 3px #77f;
}

HTML

<p class="red">This paragraph has red text.</p>
<p class="red yellow-bg">This paragraph has red text and a yellow background.</p>
<p class="red fancy">This paragraph has red text and "fancy" styling.</p>
<p>This is just a regular paragraph.</p>

Result

Specifications

Specification Status Comment
Selectors Level 4The definition of 'class selectors' in that specification. Working Draft No changes
Selectors Level 3The definition of 'class selectors' in that specification. Recommendation
CSS Level 2 (Revision 1)The definition of 'child selectors' in that specification. Recommendation
CSS Level 1The definition of 'child selectors' in that specification. Recommendation Initial definition

Browser compatibility

Update compatibility data on GitHub

Desktop Mobile
Chrome Edge Firefox Internet Explorer Opera Safari Android webview Chrome for Android Firefox for Android Opera for Android Safari on iOS Samsung Internet
Class selector (.className) Chrome

Full support 1

Edge

Full support 12

Firefox

Full support 1

IE

Full support 3

Opera

Full support 3.5

Safari

Full support 1

WebView Android

Full support ≤37

Chrome Android

Full support 18

Firefox Android

Full support 4

Opera Android

Full support 10.1

Safari iOS

Full support 1

Samsung Internet Android

Full support 1.0

Legend

Full support  
Full support