Skip to main content

CSS Selectors

CSS Element Selector

Written by Updated CSS Element Selector exercises

Select HTML elements by tag name and understand when a broad type selector is appropriate for document defaults and base styles.

The element selector styles every element of one type. Write p in your CSS, and every paragraph on the page changes. It is the simplest selector, and the right one for site-wide defaults.

It is also called a type selector. When you want to style only some paragraphs, use a CSS Class Selector instead. To style several element types with one rule, see the CSS Group Selector.

Element Selector Syntax

css

element {
    property: value;
}

Element Selector Example

css

p {
color: blue;
font-size: 18px;
}

Every <p> on the page becomes blue and 18px.

Where element selectors shine

Use them for the base look of the whole site: readable paragraphs, heading sizes, link colors, list spacing.

Sensible site-wide defaults

css

body { font-family: system-ui, sans-serif; line-height: 1.6; }
h1, h2, h3 { line-height: 1.2; }
img { max-width: 100%; height: auto; }
a { color: #0f766e; }

Where they cause trouble

Because they match every element of that type, they reach places you did not expect: a button { background: blue; } rule also hits the buttons inside a third-party widget. Keep broad rules for defaults, low in the cascade, and use classes for anything that belongs to one component.

They are also the weakest selector. A class always beats an element selector, which is usually what you want: the default can be overridden easily.

Complete CSS Element Selector Example

html

<!DOCTYPE html>
<html>
<head>
    <title>CSS Element Selector</title>
    <style>
        h1 {
            color: blue;
        }

        p {
            color: green;
            font-size: 18px;
        }
    </style>
</head>
<body>

    <h1>Element Selector Example</h1>

    <p>This is the first paragraph.</p>
    <p>This is the second paragraph.</p>

</body>
</html>

The heading turns blue, and every paragraph turns green with a larger font, without adding a single class to the HTML.

Browser Support

Feature
Chrome
Edge
Firefox
Safari
Type selector11211

Versions show the first stable desktop release with unprefixed support. Data source: MDN Browser Compatibility Data 8.0.8.

Good to know

  • Element names are not case-sensitive in HTML: P and p both work. Lowercase is the convention.
  • div { ... } styles every div on the page, which almost never makes sense. Reach for a class instead.

CSS Element Selector exercises

Every paragraph

Make every paragraph navy.

The HTML your code works on
<h1>Garden</h1>
<p>Roses bloom.</p>
<p>Tulips too.</p>
<div>Box</div>
<span>tag</span>

Result

Check your answer to see it here.