Menu
×
   ❮     
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C C++ C# BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS DSA TYPESCRIPT ANGULAR ANGULARJS GIT POSTGRESQL MONGODB ASP AI R GO KOTLIN SWIFT SASS VUE GEN AI SCIPY AWS CYBERSECURITY DATA SCIENCE INTRO TO PROGRAMMING BASH RUST

Web Development - CSS Selectors


CSS Selectors

CSS selectors are patterns used to target the HTML elements you want to style.
Once selected, you apply styles with properties and values.


Basic Selectors

The most common selectors are element, class, and ID.

Example

Element selector:

/* Targets all <p> elements */
p {
  color: steelblue;
}

Example

Class selector:

/* Targets elements with class='note' */
.note {
  background: #fff8c4;
  padding: 8px;
}

Example

ID selector:

/* Targets the element with id='header' */
#header {
  text-align: center;
}

Tip: Use classes for reusable styles. IDs should be unique per page.


Grouping Selectors

Grouping lets you style multiple selectors at once by separating them with a comma.
This helps you apply the same style to different elements in a single rule.

Example

h1,
h2,
h3 {
  font-family: Arial;
  margin-bottom: 0.5rem;
}
Try it Yourself »

Specificity - Which Rule Wins

When multiple rules match, CSS uses specificity to decide which one applies.

  • Inline styles: highest
  • ID selectors: high
  • Class selectors: medium
  • Element selectors: low

Example

Specificity in action:

<style>
p { color: black; /* low */ }
.message { color: green; /* medium */ }
#notice { color: orange; /* high */ }
</style>

<p id="notice" class="message">Text</p> <!-- orange wins -->
Try it Yourself »

Tip: Prefer classes over IDs for styling. Reserve IDs for unique anchors and JavaScript hooks.


Best Practices

  • Keep selectors short and meaningful.
  • Use class selectors for reusable patterns.
  • Group selectors that share identical declarations.

You will learn more about advanced selectors in a later chapter.

Tip: For a list of all valid CSS Selectors, go to our CSS Selectors Reference.

Next, you'll learn about CSS Colors - applying color with names, HEX, RGB, and HSL, plus background and text colors.

Next » CSS Colors


×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
sales@w3schools.com

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
help@w3schools.com

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookies and privacy policy.

Copyright 1999-2025 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.