Skip to content

Try our new Crash Courses!

Buy one of our new Crash Courses, now hosted on Podia.

ID selector – CSS

Demo

Summary

HTML code:

<p id="id-name">Paragraph text with id attribute.</p>

CSS code:

#id-name {
  /* Insert code here */
}

Details

The ID selector allows you to apply CSS styles to a single element on an HTML page that has the ID name in its ID attribute.

Notice in the CSS file that the ID name is prefixed with a hash symbol.

In the example below, the CSS styles are only applied to the first paragraph because it’s the only element that contains the ID.

<p id="important-note">First paragraph.</p>
<p>Next paragraph.</p>
<p>Last paragraph.</p>
#important-note {
  color: red;
}

id values must be unique and can only be used on one element at a time. In the example below, the same id value is used on a heading and a paragraph element. This won’t work. Instead, the heading should have one id value and the paragraph should have a different id value.

<!-- This won't work -->
<h1 id="id-name">Heading with an id value.</h1>
<p id="id-name">Paragraph text with the same id value.</p>

Exercises

Recreate the HTML and CSS code from the Demo section in your HTML and CSS files.

References

ID selectors on MDN

Back to: CSS Reference > CSS Selectors