CSS Selectors

A selector tells CSS which HTML elements to style. Good use of selectors keeps your CSS short and clean.


Basic selectors

SelectorExampleSelects
ElementpAll p elements
Class.noteAll elements with class="note"
ID#headerThe element with id="header"
Universal*All elements
Grouph1, h2, pAll the listed elements
p { color: gray; }            /* element */
.note { background: #fff3cd; }  /* class */
#header { font-size: 28px; }    /* id */
* { box-sizing: border-box; }   /* universal */
h1, h2 { color: navy; }         /* group */

Read the interview questions What is the CSS class selector? and What is grouping in CSS?


Combinators

SelectorExampleSelects
Descendant (space)div pAll p inside a div, at any depth
Child (>)div > pOnly p that are direct children of a div
Adjacent sibling (+)h2 + pThe first p right after an h2
General sibling (~)h2 ~ pAll p after an h2, with the same parent
div p { color: green; }
div > p { font-weight: bold; }
h2 + p { font-size: 20px; }
What the rules above do

I am a direct child of div (bold and green).

I am inside a section in the div (green only).

Read the interview question What are child selectors?


Attribute selectors

a[target="_blank"] { color: red; }      /* links that open in a new tab */
input[type="text"] { border: 1px solid gray; }
a[href^="https"] { color: green; }       /* href starts with https */
a[href$=".pdf"] { color: purple; }       /* href ends with .pdf */

Pseudo-classes and pseudo-elements

These select a state or a part of an element, like a:hover or p::first-line. See Pseudo-classes and pseudo-elements.


Summary

  • Use element, class and id selectors for most work.
  • Combinators select elements by their place in the HTML.
  • Attribute selectors select by attributes.
  • Next: CSS Specificity.

Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
What is the CSS class selector?
What is grouping in CSS and what is it used for?
What are child selectors in CSS?
What is the difference between id and class selector in CSS?
What is specificity in CSS?
What does !important do in CSS?
What are pseudo-classes and pseudo-elements in CSS?