• Skip to main content
  • Select language
  • Skip to search
MDN Web Docs
  • Technologies
    • HTML
    • CSS
    • JavaScript
    • Graphics
    • HTTP
    • APIs / DOM
    • WebExtensions
    • MathML
  • References & Guides
    • Learn web development
    • Tutorials
    • References
    • Developer Guides
    • Accessibility
    • Game development
    • ...more docs
Learn web development
  1. MDN
  2. Learn web development
  3. CSS
  4. Introduction to CSS
  5. Simple selectors

Simple selectors

In This Article
  1. Type selectors aka element selectors
  2. Active learning: Selecting different elements
  3. Class selectors
  4. Active learning: Handling multiple classes
  5. ID selectors
  6. Active learning: assigning the winner's colors with IDs
  7. Universal selector
  8. Combinators
  9. In the next article
Previous Overview: Introduction to CSS Next

 

In our first selectors article we'll learn about "simple" selectors, so-called because they directly match one or more elements of a document, based on the type of element (or its class or id.)

Type selectors aka element selectors

This selector is just a case-insensitive match between the selector name and a given HTML element name. This is the simplest way to target all elements of a given type. Let's take a look at an example:

Here is some HTML:

<p>What color do you like?</p>
<div>I like blue.</div>
<p>I prefer red!</p>

A simple style sheet:

/* All p elements are red */
p {
  color: red;
}
/* All div elements are blue */
div {
  color: blue;
}

And we get this:

Active learning: Selecting different elements

For this active learning, we'd like you to try changing the selector on the single CSS rule so that different elements in the example are styled. Do you know how to write a selector to apply the ruleset to multiple elements at once?

If you make a mistake, you can always reset it using the Reset button. If you get really stuck, press the Show solution button to see a potential answer.

Playable code
<div class="body-wrapper" style="font-family: 'Open Sans Light',Helvetica,Arial,sans-serif;">
  <h2>HTML Input</h2>
  <textarea id="code" class="html-input" style="width: 90%;height: 10em;padding: 10px;border: 1px solid #0095dd;"><h1>Hello World!</h1>
<p>This is a paragraph.</p>
<ul>
  <li>This is</li>
  <li>A list</li>
</ul></textarea>
  <h2>CSS Input</h2>
  <textarea id="code" class="css-input" style="width: 90%;height: 10em;padding: 10px;border: 1px solid #0095dd;">h1 {
  color: red;
  text-shadow: 1px 1px 1px black;
  background: linear-gradient(to bottom, rgba(0,0,0,0.25), rgba(0,0,0,0.1));
  padding: 3px;
  text-align: center;
  box-shadow: inset 2px 2px 5px rgba(0,0,0,0.5), inset -2px -2px 5px rgba(255,255,255,0.5);
}</textarea>
  <h2>Output</h2>
  <div class="output" style="width: 90%;height: 10em;padding: 10px;border: 1px solid #0095dd;"></div>
  <div class="controls">
    <input id="reset" type="button" value="Reset" style="margin: 10px 10px 0 0;">
    <input id="solution" type="button" value="Show solution" style="margin: 10px 0 0 10px;">
  </div>
</div>
var htmlInput = document.querySelector(".html-input");
var cssInput = document.querySelector(".css-input");
var reset = document.getElementById("reset");
var htmlCode = htmlInput.value;
var cssCode = cssInput.value;
var output = document.querySelector(".output");
var solution = document.getElementById("solution");
var styleElem = document.createElement('style');
var headElem = document.querySelector('head');
headElem.appendChild(styleElem);
function drawOutput() {
  output.innerHTML = htmlInput.value;
  styleElem.textContent = cssInput.value;
}
reset.addEventListener("click", function() {
  htmlInput.value = htmlCode;
  cssInput.value = cssCode;
  drawOutput();
});
solution.addEventListener("click", function() {
  htmlInput.value = htmlCode;
  cssInput.value = 'p {\n  color: red;\n  text-shadow: 1px 1px 1px black;\n  background: linear-gradient(to bottom, rgba(0,0,0,0.25), rgba(0,0,0,0.1));\n  padding: 3px;\n  text-align: center;\n  box-shadow: inset 2px 2px 5px rgba(0,0,0,0.5), inset -2px -2px 5px rgba(255,255,255,0.5);\n}';
  drawOutput();
});
htmlInput.addEventListener("input", drawOutput);
cssInput.addEventListener("input", drawOutput);
window.addEventListener("load", drawOutput);

Class selectors

The class selector consists of a dot, '.', followed by a class name. A class name is any value without spaces put within an HTML class attribute. It is up to you to choose a name for the class. It is also worth knowing that multiple elements in a document can have the same class value and a single element can have multiple class names separated by white space. Here's a quick example:

Here is some HTML:

<ul>
  <li class="first done">Create an HTML document</li>
  <li class="second done">Create a CSS style sheet</li>
  <li class="third">Link them all together</li>
</ul>

A simple style sheet:

/* The element with the class "first" is bolded */
.first {
  font-weight: bold;
}
/* All the elements with the class "done" are strike through */
.done {
  text-decoration: line-through;
}

And we get this result:

Active learning: Handling multiple classes

For this active learning, we'd like you to try changing the class attributes on the paragraph elements so that you can apply multiple separate effects. Try applying a base-box class plus a role class (editor-note or warning), and optionally important if you want to give the box strong importance. Think about how this kind of rule set allows you to build up a modular system of styles.

If you make a mistake, you can always reset it using the Reset button. If you get really stuck, press the Show solution button to see a potential answer.

Playable code 2
<div class="body-wrapper" style="font-family: 'Open Sans Light',Helvetica,Arial,sans-serif;">
  <h2>HTML Input</h2>
  <textarea id="code" class="html-input" style="width: 90%;height: 10em;padding: 10px;border: 1px solid #0095dd;"><p class="">My first paragraph.</p>
<p class="">My second paragraph.</p>
<p class="">My third paragraph</p></textarea>
  <h2>CSS Input</h2>
  <textarea id="code" class="css-input" style="width: 90%;height: 12em;padding: 10px;border: 1px solid #0095dd;">.base-box {
  background-image: linear-gradient(to bottom, rgba(0,0,0,0.1), rgba(0,0,0,0.3));
  padding: 3px 3px 3px 7px;
}
.important {
  font-weight: bold;
}
.editor-note {
  background-color: #9999ff;
  border-left: 6px solid #333399;
}
.warning {
  background-color: #ff9999;
  border-left: 6px solid #993333;
}</textarea>
  <h2>Output</h2>
  <div class="output" style="width: 90%;height: 10em;padding: 10px;border: 1px solid #0095dd;"></div>
  <div class="controls">
    <input id="reset" type="button" value="Reset" style="margin: 10px 10px 0 0;">
    <input id="solution" type="button" value="Show solution" style="margin: 10px 0 0 10px;">
  </div>
</div>
var htmlInput = document.querySelector(".html-input");
var cssInput = document.querySelector(".css-input");
var reset = document.getElementById("reset");
var htmlCode = htmlInput.value;
var cssCode = cssInput.value;
var output = document.querySelector(".output");
var solution = document.getElementById("solution");
var styleElem = document.createElement('style');
var headElem = document.querySelector('head');
headElem.appendChild(styleElem);
function drawOutput() {
  output.innerHTML = htmlInput.value;
  styleElem.textContent = cssInput.value;
}
reset.addEventListener("click", function() {
  htmlInput.value = htmlCode;
  cssInput.value = cssCode;
  drawOutput();
});
solution.addEventListener("click", function() {
  htmlInput.value = '<p class="base-box warning important">My first paragraph.</p>\n\n<p class="">My second paragraph.</p>\n\n<p class="">My third paragraph</p>';
  cssInput.value = cssCode;
  drawOutput();
});
htmlInput.addEventListener("input", drawOutput);
cssInput.addEventListener("input", drawOutput);
window.addEventListener("load", drawOutput);

ID selectors

The ID selector consists of a hash/pound symbol (#), followed by the ID name of a given element. Any element can have a unique ID name set with the id attribute. It is up to you what name you choose for the ID. It's the most efficient way to select a single element.

Important: An ID name must be unique in the document. Behaviors regarding duplicated IDs are unpredictable, for example in some browsers only the first instance is counted, and the rest are ignored.

Let's look at a quick example — here is some HTML:

<p id="polite"> — "Good morning."</p>
<p id="rude"> — "Go away!"</p>

A simple style sheet:

#polite {
  font-family: cursive;
}
#rude {
  font-family: monospace;
  text-transform: uppercase;
}

And we get this as an output:

Active learning: assigning the winner's colors with IDs

For this active learning, we'd like you to give the winner, second and third place in the competition an appropriate gold, silver and bronze color by giving CSS rules 2–4 appropriate selectors that select the relevant elements based on their ID.

If you make a mistake, you can always reset it using the Reset button. If you get really stuck, press the Show solution button to see a potential answer.

Playable code 3
<div class="body-wrapper" style="font-family: 'Open Sans Light',Helvetica,Arial,sans-serif;">
  <h2>HTML Input</h2>
  <textarea id="code" class="html-input" style="width: 90%;height: 10em;padding: 10px;border: 1px solid #0095dd;"><p id="first"><strong>Winner</strong>: Velma Victory</p>
<p id="second"><strong>2nd</strong>: Colin Contender</p>
<p id="third"><strong>3rd</strong>: Phoebe Player</p></textarea>
  <h2>CSS Input</h2>
  <textarea id="code" class="css-input" style="width: 90%;height: 10em;padding: 10px;border: 1px solid #0095dd;">p {
  text-transform: uppercase;
  padding: 5px;
}
 {
  background-color: goldenrod;
}
 {
  background-color: silver;
}
 {
  background-color: #CD7F32;
}</textarea>
  <h2>Output</h2>
  <div class="output" style="width: 90%;height: 10em;padding: 10px;border: 1px solid #0095dd;"></div>
  <div class="controls">
    <input id="reset" type="button" value="Reset" style="margin: 10px 10px 0 0;">
    <input id="solution" type="button" value="Show solution" style="margin: 10px 0 0 10px;">
  </div>
</div>
var htmlInput = document.querySelector(".html-input");
var cssInput = document.querySelector(".css-input");
var reset = document.getElementById("reset");
var htmlCode = htmlInput.value;
var cssCode = cssInput.value;
var output = document.querySelector(".output");
var solution = document.getElementById("solution");
var styleElem = document.createElement('style');
var headElem = document.querySelector('head');
headElem.appendChild(styleElem);
function drawOutput() {
  output.innerHTML = htmlInput.value;
  styleElem.textContent = cssInput.value;
}
reset.addEventListener("click", function() {
  htmlInput.value = htmlCode;
  cssInput.value = cssCode;
  drawOutput();
});
solution.addEventListener("click", function() {
  htmlInput.value = htmlCode;
  cssInput.value = 'p {\n  text-transform: uppercase;\n  padding: 5px;\n}\n\n#first {\n  background-color: goldenrod;\n}\n\n#second {\n  background-color: silver;\n}\n\n#third {\n  background-color: #CD7F32;\n}';
  drawOutput();
});
htmlInput.addEventListener("input", drawOutput);
cssInput.addEventListener("input", drawOutput);
window.addEventListener("load", drawOutput);

Universal selector

The universal selector (*) is the ultimate joker. It allows selecting all elements in a page. As it is rarely useful to apply a style to every element on a page, it is often used in combination with other selectors (see Combinators below.)

Important: Careful when using the universal selector. As it applies to all elements, using it in large web pages can have a perceptible impact on performance: web pages can be displayed slower than expected. There are not many instances where you'd want to use this selector.

Now for an example; first some HTML:

<div>
  <p>I think the containing box just needed
  a <strong>border</strong> or <em>something</em>,
  but this is getting <strong>out of hand</strong>!</p>
</div>

And a simple style sheet:

* {
  padding: 5px;
  border: 1px solid black;
  background: rgba(255,0,0,0.25)
}

Together, these give the following result:

Combinators

In CSS, combinators allow you to combine multiple selectors together, which allows you to select elements inside other elements, or adjacent to other elements. The four available types are:

  • The descendant selector —  (space) — allows you to select an element nested somewhere inside another element (not necessarily a direct descendant; it could be a grandchild, for example)
  • The child selector — > — allows you to select an element that is an immediate child of another element.
  • The adjacent sibling selector — + — allows you to select an element that is an immediate sibling of another element (i.e. right next to it, at the same level in the hierarchy).
  • The general sibling selector — ~ — allows you to select any elements that are siblings of another element (i.e. at the same level in the hierarchy, but not necessarily right next to it).

Here is a quick example to show you how these work:

<section>
  <h2>Heading 1</h2>
  <p>Paragraph 1</p>
  <p>Paragraph 2</p>
  <div>
    <h2>Heading 2</h2>
    <p>Paragraph 3</p>
    <p>Paragraph 4</p>
  </div>
</section>
section p {
  color: blue;
}
section > p {
  background-color: yellow;
}
h2 + p {
  text-transform: uppercase;
}
h2 ~ p {
  border: 1px dashed black;
}

The CSS styles the HTML as shown below:

The selectors work like so:

  • section p selects all the <p> elements — both the first two that are direct children of the <section> element, and the second two that are grandchildren of the <section> element (they are inside the <div> as well). All the paragraph text is therefore colored blue.
  • section > p selects only the first two <p> elements, which are direct children of the <section> element (but not the second two, which are not direct children). Only the first two paragraphs therefore have a yellow background color.
  • h2 + p selects only <p> elements that come directly after <h2> elements on the same hierarchy level — in this case the first and third paragraphs. These ones therefore have text all in uppercase.
  • h2 ~ p selects any <p> elements on the same hierarchy level as (and coming after) <h2> elements — in this case all the paragraphs. All of them therefore have a dashed border.

In the next article

Well done for reaching the end of our first selectors tutorial! I hope you found your first play with selectors fun — now we've looked at the simple core selectors we'll use most commonly, let's start looking at some more advanced features, starting with Attribute selectors.

Previous Overview: Introduction to CSS Next

 

Document Tags and Contributors

Tags: 
  • Article
  • Beginner
  • Class
  • CSS
  • Element
  • Guide
  • id
  • Learn
  • Selectors
  • Type
  • universal
 Contributors to this page: cumanacr, mike706574, chrisdavidmills, lvnam96
 Last updated by: cumanacr, May 3, 2017, 9:13:21 PM
See also
  1. Complete beginners start here!
  2. Getting started with the Web
    1. Getting started with the Web overview
    2. Installing basic software
    3. What will your website look like?
    4. Dealing with files
    5. HTML basics
    6. CSS basics
    7. JavaScript basics
    8. Publishing your website
    9. How the Web works
  3. HTML — Structuring the Web
  4. Introduction to HTML
    1. Introduction to HTML overview
    2. Getting started with HTML
    3. What's in the head? Metadata in HTML
    4. HTML text fundamentals
    5. Creating hyperlinks
    6. Advanced text formatting
    7. Document and website structure
    8. Debugging HTML
    9. Assessment: Marking up a letter
    10. Assessment: Structuring a page of content
  5. Multimedia and embedding
    1. Multimedia and embedding overview
    2. Images in HTML
    3. Video and audio content
    4. From object to iframe — other embedding technologies
    5. Adding vector graphics to the Web
    6. Responsive images
    7. Assessment: Mozilla splash page
  6. HTML tables
    1. HTML tables overview
    2. HTML table basics
    3. HTML Table advanced features and accessibility
    4. Assessment: Structuring planet data
  7. CSS — Styling the Web
  8. Introduction to CSS
    1. Introduction to CSS overview
    2. How CSS works
    3. CSS syntax
    4. Selectors introduction
    5. Simple selectors
    6. Attribute selectors
    7. Pseudo-classes and pseudo-elements
    8. Combinators and multiple selectors
    9. CSS values and units
    10. Cascade and inheritance
    11. The box model
    12. Debugging CSS
    13. Assessment: Fundamental CSS comprehension
  9. Styling text
    1. Styling text overview
    2. Fundamental text and font styling
    3. Styling lists
    4. Styling links
    5. Web fonts
    6. Assessment: Typesetting a community school homepage
  10. Styling boxes
    1. Styling boxes overview
    2. Box model recap
    3. Backgrounds
    4. Borders
    5. Styling tables
    6. Advanced box effects
    7. Assessment: Creating fancy letterheaded paper
    8. Assessment: A cool-looking box
  11. CSS layout
    1. CSS layout overview
    2. Introduction
    3. Floats
    4. Positioning
    5. Practical positioning examples
    6. Flexbox
    7. Grids
  12. JavaScript — Dynamic client-side scripting
  13. JavaScript first steps
    1. JavaScript first steps overview
    2. What is JavaScript?
    3. A first splash into JavaScript
    4. What went wrong? Troubleshooting JavaScript
    5. Storing the information you need — Variables
    6. Basic in JavaScript — Numbers and operators
    7. Handling text — Strings in JavaScript
    8. Useful string methods
    9. Arrays
    10. Assessment: Silly story generator
  14. JavaScript building blocks
    1. JavaScript building blocks overview
    2. Making decisions in your code — Conditionals
    3. Looping code
    4. Functions — Reusable blocks of code
    5. Build your own function
    6. Function return values
    7. Introduction to events
    8. Assessment: Image gallery
  15. Introducing JavaScript objects
    1. Introducing JavaScript objects overview
    2. Object basics
    3. Object-oriented JavaScript for beginners
    4. Object prototypes
    5. Inheritance in JavaScript
    6. Working with JSON data
    7. Object building practise
    8. Assessment: Adding features to our bouncing balls demo
  16. Accessibility — Make the web usable by everyone
  17. Accessibility guides
    1. Accessibility overview
    2. What is accessibility?
    3. HTML: A good basis for accessibility
    4. CSS and JavaScript accessibility best practices
    5. WAI-ARIA basics
    6. Accessible multimedia
    7. Mobile accessibility
  18. Accessibility assessment
    1. Assessment: Accessibility troubleshooting
  19. Tools and testing
  20. Cross browser testing
    1. Cross browser testing overview
    2. Introduction to cross browser testing
    3. Strategies for carrying out testing
    4. Handling common HTML and CSS problems
    5. Handling common JavaScript problems
    6. Handling common accessibility problems
    7. Implementing feature detection
    8. Introduction to automated testing
    9. Setting up your own test automation environment
  21. Server-side website programming
  22. First steps
    1. First steps overview
    2. Introduction to the server-side
    3. Client-Server overview
    4. Server-side web frameworks
    5. Website security
  23. Django web framework (Python)
    1. Django web framework (Python) overview
    2. Introduction
    3. Setting up a development environment
    4. Tutorial: The Local Library website
    5. Tutorial Part 2: Creating a skeleton website
    6. Tutorial Part 3: Using models
    7. Tutorial Part 4: Django admin site
    8. Tutorial Part 5: Creating our home page
    9. Tutorial Part 6: Generic list and detail views
    10. Tutorial Part 7: Sessions framework
    11. Tutorial Part 8: User authentication and permissions
    12. Tutorial Part 9: Working with forms
    13. Tutorial Part 10: Testing a Django web application
    14. Tutorial Part 11: Deploying Django to production
    15. Web application security
    16. Assessment: DIY mini blog
  24. Express Web Framework (node.js/JavaScript)
    1. Express Web Framework (Node.js/JavaScript) overview
    2. Express/Node introduction
    3. Setting up a Node (Express) development environment
    4. Express tutorial: The Local Library website
    5. Express Tutorial Part 2: Creating a skeleton website
    6. Express Tutorial Part 3: Using a database (with Mongoose)
    7. Express Tutorial Part 4: Routes and controllers
    8. Express Tutorial Part 5: Displaying library data
    9. Express Tutorial Part 6: Working with forms
    10. Express Tutorial Part 7: Deploying to production
  25. Further resources
  26. Advanced learning material
    1. WebGL: Graphics processing
  27. Common questions
    1. HTML questions
    2. CSS questions
    3. JavaScript questions
    4. How the Web works
    5. Tools and setup
    6. Design and accessibility
  28. How to contribute