Skip to main content

How to Select Elements by Tag Name in CSS

· 3 min read
Jagdish Kumawat
Founder @ Dewiride

A type selector styles every element of one kind: write the tag name on its own. p { ... } styles every paragraph on the page.

Syntax​

Syntax
<element name> {
<declarations>
}
PartWhat it does
<element name>The tag name without the angle brackets, such as p for paragraphs.
<declarations>The styles every element of that kind gets.

MDN's Type selectors page explains that a type selector selects all elements of the given type in the document.

The Example​

The example is a page of opening hours: a heading and two paragraphs. One rule colors every paragraph grey.

Step 1: Write the Code​

Create a file named index.html in a text editor, such as Visual Studio Code:

index.html, an HTML page with a style element holding a rule for p that sets the color 616161, and a body with the heading Opening hours and two paragraphs.

index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Type selector</title>
<style>
p {
color: #616161;
}
</style>
</head>
<body>
<h1>Opening hours</h1>
<p>Monday to Friday, 9:00 to 17:00.</p>
<p>Closed on public holidays.</p>
</body>
</html>

The selector p matches every p element, so both paragraphs get the color #616161.

Step 2: Open It in a Browser​

Double-click index.html. It opens in your browser:

The page in Chromium: the heading Opening hours in black, then Monday to Friday, 9:00 to 17:00. and Closed on public holidays. in grey.

The screenshot comes from Chromium 159, the open-source browser that Chrome is built on.

What Happened​

  • Both paragraphs are grey. Chromium gave them the color rgb(97, 97, 97), which is #616161.
  • The heading stayed black. It's an h1, not a p.

Common Mistakes​

MistakeWhat happensDo this instead
Writing the angle brackets: <p><p> isn't a valid selector, so Chromium dropped the rule and the paragraph stayed blackWrite only the name: p
Adding a dot: .pThe dot makes it a class selector for class="p", which no element hadLeave out the dot

Troubleshooting​

SymptomLikely causeFix
Nothing changesThe selector has angle brackets or a dotWrite the bare tag name
Elements you didn't mean to style changedA type selector matches every element of that kindGive the ones you want a class, and select the class

FAQ​

Does the case of the tag name matter?​

Not in an HTML page: P styled the paragraph just like p.

How do I style only some of the paragraphs?​

Give those paragraphs a class in the HTML and select the class with a dot, such as .note. A type selector always matches all of them.

Conclusion​

Write the tag name on its own, with no brackets and no dot, and the rule styles every element of that kind on the page.

Additional Resources​