Search

What are the different types of Selectors in CSS?

  • Share this:

CSS selectors are used to select elements in an HTML document and apply styles to them. There are several different types of CSS selectors, each with its own specific syntax and use case.

Here are some common types of CSS selectors:

Type Selectors

These selectors match elements based on their HTML tag name. For example, the `p` selector matches all `p` (paragraph) elements in the document.

p {
  color: red;
}

Class Selectors

These selectors match elements based on their class attributes. For example, the `.warning` selector matches all elements with the `warning` class.

.warning {
  color: orange;
}

ID selectors

These selectors match elements based on their ID attribute. For example, the `#header` selector matches the element with the `header` ID.

#header {
  background-color: blue;
}

Attribute Selectors

These selectors match elements based on their attributes or attribute values. For example, the `[href]` selector matches all elements with an `href` attribute, and the `[href="https://example.com"]` selector matches all elements with an `href` attribute equal to `"https://example.com"`.

[href] {
  color: green;
}

[href="https://example.com"] {
  color: red;
}

Pseudo-class Selectors

These selectors match elements based on their state or position in the document. For example, the `:hover` pseudo-class selector matches elements that are being hovered over by the user's cursor, and the `:first-child` pseudo-class selector matches the first child element of its parent.

a:hover {
  color: blue;
}

li:first-child {
  font-weight: bold;
}

Pseudo-element Selectors

These selectors match specific parts of an element. For example, the `::before` pseudo-element selector matches the content before an element and the `::after` pseudo-element selector matches the content after an element.

h1::before {
  content: "Chapter 1: ";
}

p::after {
  content: " - The end";
}

These are just a few examples of the many different types of CSS selectors that are available. By using the appropriate selector, web designers and developers can apply styles to specific elements or groups of elements in an HTML document.

 

Tags:

About author
I am a professional web developer. I love programming and coding, and reading books. I am the founder and CEO of StorialTech.