Back to all posts

CSS: Selectors


CSS Selectors are patterns used to select and applay styles to specific HTML element in a web page. A CSS selector can target elements based on their tags name, class, ID, attributes, and their relationship to other element in the document.

In short, CSS selectors used to find the HTML element you want to style.

We can divide selectors into five categories.

1. Simple Selectors
Simple selectors are CSS selectors that match one or more elements based on their tag name, class name, or ID

/*
* Example
*/
p {
  color: blue;
}

Continue reading with example


2. Combinator selectors

Combinator selectors are used in CSS to select specific elements based on their relationship to other element in the HTML document.

There are 4 types.

/*
* Example
*/
ul > li {
  color:red;
}

Continue reading with example


3. Attribute selectors

Attribute selector is CSS are used to select and style elements based on their attributes and attributes values.
They allow you to target specific value for an attribute.

/*
* Example
*/
input[type="text"] {
  background-color: lightgray;
}

4. Pseude-class selectors

Pseude-class selector are used in CSS to style elements based on there state or position within the document.
They start with a colon(:) followed by a keyword or a parameter.

/*
* Example
*/
button:hover {
  background-color: red;
}

5. Pseude-element selectors

Peude-element selectors are used in CSS to style specific parts of an element’s content.
They start with a double colon (::) followed by a keyword.

/*
* Example
*/
p::before {
  content: "Before: ";
  font-weight: bold;
}

CSS selectors are a fundament part of styling web pages, and understanding them is essential for creating effective and maintainable stylesheets.