CSS Selectors

What Are CSS Selectors?

Selectors are used in CSS to target specific HTML elements and apply styles to them. For example, the selector p applies styles to all paragraphs.

Basic Selectors

Basic selectors are the foundation of CSS. They allow you to target elements by name, class, ID, or apply styles to everything.

Type Selector

Targets all elements of a specific type:

p {
        color: red;
        }

Class Selector

Targets any element with the specified class. Use a dot . followed by the class name:

.note {
        font-style: italic;
        }

ID Selector

Targets a single, unique element by its ID. Use a hash # before the ID name:

#header {
        background-color: lightgray;
        }

Universal Selector

Targets every element on the page. Commonly used to reset default styles:

* {
        margin: 0;
        padding: 0;
        }

Grouping Selectors

Use commas to apply the same style to multiple selectors:

h1, h2, p {
  font-family: Arial;
}

Combinators (Descendant, Child, Sibling)

  • div p – selects all <p> inside a <div>
  • div > p – selects only direct child <p> elements of a <div>
  • h1 + p – selects the first <p> after an <h1>
  • h1 ~ p – selects all <p> siblings after an <h1>

Attribute Selectors

Target elements based on attribute values:

input[type="text"] {
  border: 1px solid #ccc;
}

a[href^="https"] {
  color: green;
}

img[alt$=".jpg"] {
  border-radius: 5px;
}

Pseudo-classes

Style elements based on state or position:

  • a:hover – when a link is hovered
  • li:first-child – the first list item
  • p:nth-child(2) – the second child element that is a <p>

Practice Prompt

Create a CSS block using the following selectors:

  • h2 — set color to blue
  • .note — italicize and gray color
  • #main-box — set background to light yellow
  • input[type="text"] — add padding
  • li:first-child — bold the text
h2 {
  color: blue;
}

.note {
  color: gray;
  font-style: italic;
}

#main-box {
  background-color: #ffffcc;
}

input[type="text"] {
  padding: 5px;
}

li:first-child {
  font-weight: bold;
}

Need Help?

Ask the AI if you need help understanding or want to dive deeper in any topic