CSS Selectors

CSS selectors are used to target HTML elements for styling. This page covers different types of CSS selectors and how to use them.

Types of CSS Selectors

CSS selectors are categorized based on how they target elements. Here are some commonly used selectors:

Element Selector

Targets elements by their tag name.


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

        

Styles all <p> elements with color: blue;.

Class Selector

Targets elements with a specific class name.


/* Class Selector */
.button {
  background-color: green;
  color: white;
}

        

Styles all elements with the class button.

ID Selector

Targets a unique element with a specific ID.


/* ID Selector */
#header {
  font-size: 24px;
  font-weight: bold;
}

        

Styles the element with the ID header.

Attribute Selector

Targets elements based on their attributes and values.


/* Attribute Selector */
input[type="text"] {
  border: 1px solid gray;
}

        

Styles <input> elements with type="text".

Group Selector

Applies the same style to multiple elements.


/* Group Selector */
h1, h2, h3 {
  color: darkblue;
}

        

Styles <h1>, <h2>, and <h3> elements with color: darkblue;.

Descendant Selector

Targets elements nested within other elements.


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

        

Styles <p> elements inside a <div> with color: red;.

Pseudo-class Selector

Targets elements based on their state or position.


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

        

Styles <a> elements when hovered over with color: orange;.

Pseudo-element Selector

Targets specific parts of an element.


/* Pseudo-element Selector */
p::first-line {
  font-weight: bold;
}

        

Styles the first line of all <p> elements with font-weight: bold;.