CSSSelectors Overview

Selectors Overview

CSS selectors target HTML elements to apply styles. Selectors can be simple (element, class, ID), combined (descendant, child), or complex (attribute, pseudo-class). Understanding selectors is fundamental to writing effective CSS.

Selector Types

Type

Example

Selects

Element

div

All div elements

Class

.button

Elements with class="button"

ID

#header

Element with id="header"

Attribute

[type="text"]

Elements with matching attribute

Pseudo-class

a:hover

Elements in specific state

Pseudo-element

p::first-line

Specific part of element

Combinator

div p

Elements with relationship

CSS
/* Element selector */
p {
  color: black;
}

/* Class selector */
.warning {
  color: red;
}

/* ID selector */
#main {
  width: 100%;
}

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

/* Universal selector */
* {
  margin: 0;
  padding: 0;
}
Selector Combinators

CSS
/* Descendant combinator */
div p {
  color: blue;
  /* All p inside div, at any depth */
}

/* Child combinator */
div > p {
  color: green;
  /* Only direct p children of div */
}

/* Adjacent sibling */
h1 + p {
  margin-top: 0;
  /* First p after h1 */
}

/* General sibling */
h1 ~ p {
  color: gray;
  /* All p after h1 */
}
Note
Selectors are patterns that target HTML elements. Basic selectors target elements, classes, IDs. Combinators show element relationships. Master these fundamentals to write effective CSS.
Next
Type, class, ID selectors: [Type, Class & ID Selectors](/css/type-class-id).