Element, ID & Class

Target elements by tag name, id, and class.

Syntaxp { } .classname { } #idname { }

The three most common selectors are:

  • Element — matches every tag of that type, e.g. p.
  • Class — matches elements with a given class, written with a dot, e.g. .note.
  • ID — matches the single element with that id, written with a hash, e.g. #header.

Classes are reusable across many elements; an id should be unique on the page.

Example

Try it yourself
Loading editor…
Press Run to see the result.

When to use it

  • A developer uses the h2 element selector to apply consistent heading styles across every article page without adding classes to each tag.
  • A designer targets #main-nav with an ID selector to apply unique branding styles to the site's primary navigation bar.
  • A developer uses .btn on multiple elements (links, buttons, inputs) so a consistent button style applies regardless of the HTML tag used.

More examples

Element selector targets all tags

Applies rules to every p and h2 in the document by targeting the element type directly.

Example · css
p {
  color: #444;
  line-height: 1.6;
}
h2 {
  color: #2965f1;
  font-size: 1.5rem;
}

ID selector for unique element

Targets the single element with id="site-header" — ID selectors are unique and carry higher specificity.

Example · css
#site-header {
  background-color: #2965f1;
  color: #fff;
  padding: 16px 24px;
}

Class selector for reusable style

Defines a reusable .btn class and a modifier .btn-danger that can be combined on any HTML element.

Example · css
.btn {
  display: inline-block;
  padding: 8px 18px;
  background-color: #2965f1;
  color: #fff;
  border-radius: 4px;
  text-decoration: none;
}
.btn-danger {
  background-color: #c0392b;
}

Discussion

  • Be the first to comment on this lesson.
Element, ID & Class — CSS | SoundsCode