CSS selectorSelectors

Type selector

Selects every element with a given tag name, for example every p paragraph or every li list item.

On this page

Example

#
CSS
h2 {
  margin: 0 0 6px;
  font-size: 20px;
}

p {
  margin: 0 0 8px;
  color: #a1a1aa;
}

a {
  color: #c4b5fd;
  text-underline-offset: 3px;
}
Preview

Definition and usage

#

A type selector is just an HTML tag name, with no dot, hash, or brackets. The rule p { … } hits every paragraph on the page, and li { … } hits every list item in every list, no matter where they sit in the document. In HTML documents, the case of the tag name doesn’t matter, so P and p mean the same thing.

It has low specificity, (0, 0, 1), so it loses to any class and any ID. That makes it perfect for base styles, such as paragraph spacing, link appearance, or heading sizes, which classes can override without a fight.

You can combine a type selector with other parts of a selector: p.lead is a paragraph with the class lead, input[type="email"] is an email input field. The tag name always comes first, before the class or attribute.

Watch out for rules that are too broad. A style applied to a bare div or span touches hundreds of elements, including places you weren’t thinking of. For specific parts of the page, classes are the safer choice.

Syntax

#
Syntax
tag { property: value; }

Example selectors

#
  • p

    All paragraphs at once: both <p> elements get a purple background.
  • li

    Every list item, no matter which list it’s in.
  • a

    All links. A good place to set a shared color and underline for links across the whole page.
  • H3

    Uppercase works too, because tag names in HTML aren’t case-sensitive. Lowercase is the convention, though.

Example selectors in practice

#

p

All paragraphs at once: both <p> elements get a purple background.
p { background: #7c3aed; color: #fff; }

li

Every list item, no matter which list it’s in.
li { background: #7c3aed; color: #fff; }

a

All links. A good place to set a shared color and underline for links across the whole page.
a { background: #7c3aed; color: #fff; }

H3

Uppercase works too, because tag names in HTML aren’t case-sensitive. Lowercase is the convention, though.
H3 { background: #7c3aed; color: #fff; }

Browser support

#

Widely available

Works in all modern browsers, phones included. You can use it without worry.

  • Chrome
  • Edge
  • Firefox
  • Safari

Good practices

#
  • Keep type-selector styles at the top of the stylesheet as your base. Style specific components with classes, which are easy to override and move around.
  • Don’t style generic tags like div or span. They carry no meaning, so the rule will hit random places.
  • Only combine a type selector with a class when the class is meant to work on a single tag, for example button.link. In other cases, the class alone is more flexible.

Related entries

#

Spotted a mistake or missing an example? Write to us.