CSS Selectors - Detailed Overview

Introduction to CSS Selectors

CSS selectors are used to "select" the HTML elements you want to style. They are one of the core features of CSS, allowing you to apply styles to elements based on various attributes.

Basic Selectors

Basic selectors are used to select elements based on their name, class, or ID:

/* Element Selector */
p {
    color: blue;
}

/* Class Selector */
.special {
    color: green;
}

/* ID Selector */
#unique {
    color: red;
}

This is a paragraph styled with the element selector.

This paragraph is styled with the class selector.

This paragraph is styled with the ID selector.

Grouping Selectors

You can group multiple selectors to apply the same styles to multiple elements:

h1, h2, p {
    color: purple;
}

Heading 1 styled with a grouped selector.

Heading 2 styled with a grouped selector.

This paragraph is also styled with the same grouped selector.

Combinator Selectors

Combinator selectors are used to select elements based on a relationship between them:

/* Descendant Selector */
div p {
    color: blue;
}

/* Child Selector */
div > p {
    color: green;
}

/* Adjacent Sibling Selector */
h1 + p {
    color: red;
}

/* General Sibling Selector */
h1 ~ p {
    color: purple;
}

This paragraph is selected by the descendant selector.

This paragraph is selected by the child selector.

This is a heading.

This paragraph is selected by the adjacent sibling selector.

This paragraph is selected by the general sibling selector.

Attribute Selectors

Attribute selectors allow you to select elements based on the presence or value of an attribute:

/* Attribute Selector */
a[target] {
    color: orange;
}

/* Attribute Value Selector */
a[target="_blank"] {
    color: purple;
}

Pseudo-classes and Pseudo-elements

Pseudo-classes are used to define a special state of an element. Pseudo-elements are used to style specified parts of an element:

/* Pseudo-class Selector */
a:hover {
    color: red;
}

/* Pseudo-element Selector */
p::first-line {
    font-weight: bold;
}
Hover over this link to see the red color.

This paragraph's first line is bold.