CSS Selectors

CSS selectors are tools for selecting and styling HTML elements. They allow you to apply styles to specific elements based on their tags, classes, IDs, and other characteristics.


Types of CSS Selectors

Basic Selectors

Tag Selector
Class Selector
ID Selector
Universal Selector
Group Selector

Combinator Selectors

  • Child selector (E > F) — selects only direct descendants.
    Example: div > p selects paragraphs that are direct children of div.
  • Adjacent sibling selector (E + F) — selects the element immediately following the specified one.
    Example: h1 + p selects the first paragraph immediately after an h1 heading.
  • General sibling selector (E ~ F) — selects all elements following the specified one.
    Example: h1 ~ p selects all paragraphs following an h1.

Attribute Selectors

[attr]
[attr=value]
[attr*=value]
[attr^=value]
[attr$=value]


Selector Usage Examples

/* Tag selector */
p {
  color: red;
}

/* Class selector */
.button {
  background-color: blue;
}

/* ID selector */
#header {
  font-size: 24px;
}

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

Useful Resource