CSS Tutorial · CSS Basics · Lesson 3 of 19

CSS Selectors

Select elements by type, class, id, attribute, relationship and state.

Basic selectors

Selector Selects
p all <p> elements
.note elements with class="note"
#header the element with id="header"
* every element
h1, h2 all <h1> and <h2>

Combinators

Selector Selects
nav a <a> anywhere inside <nav> (descendant)
ul > li <li> that are direct children of <ul>
h2 + p the <p> immediately after an <h2>
input[type="email"] attribute selector
Example 1Try it yourself
<style>
  body { font-family: system-ui, sans-serif; }
  .note { background: #fef9c3; padding: 4px 8px; }
  #main-title { color: #7c3aed; }
  nav a { color: #0369a1; margin-right: 8px; }
  ul > li { font-weight: bold; }
  h2 + p { font-style: italic; }
  input[type="email"] { border: 2px solid #16a34a; }
  .card:has(img) { border: 2px dashed #f97316; padding: 6px; }
</style>
<h1 id="main-title">Selectors</h1>
<nav><a href="#">Home</a><a href="#">Docs</a></nav>
<p class="note">A note.</p>
<h2>Heading</h2>
<p>The paragraph right after the h2 is italic.</p>
<ul><li>Direct child (bold)</li></ul>
<input type="email" placeholder="email"> <input type="text" placeholder="text">
<div class="card">A card with an image: <img alt="" width="16" height="16" src="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg'/%3E"></div>

Modern selectors

:is(), :where() and :has() (the "parent selector") make complex selections short — .card:has(img) selects cards that contain an image.

Test yourself

Which selector targets elements with class="btn"?

  1. #btn
  2. .btn
  3. btn
  4. *btn
Show answer

Answer: .btn