CSS Selectors

CSS selectors are used to select HTML elements that you want to style. They define which elements a CSS rule applies to. Selectors are one of the most important concepts in CSS.

Types of CSS Selectors

There are several types of CSS selectors, each used for different purposes. Below are the most commonly used selectors in CSS.

1. Element Selector

The element selector selects all HTML elements of a specific type.

p {
  color: blue;
}

This rule applies to all <p> elements on the page.

2. Class Selector

The class selector selects elements with a specific class attribute. It is written using a dot (.) followed by the class name.

.highlight {
  background-color: yellow;
}

This rule applies to all elements with the class highlight.

3. ID Selector

The ID selector selects a single unique element. It is written using a hash (#) followed by the ID name.

#main-title {
  font-size: 32px;
}

An ID should be used only once on a page.

4. Grouping Selector

The grouping selector allows you to apply the same styles to multiple selectors at once.

h1, h2, h3 {
  font-family: Arial, sans-serif;
}

5. Universal Selector

The universal selector selects all elements on the page. It is represented by an asterisk (*).

* {
  margin: 0;
  padding: 0;
}

6. Descendant Selector

The descendant selector selects elements that are inside another element.

div p {
  color: green;
}

This rule selects all <p> elements inside a <div>.

7. Child Selector

The child selector selects elements that are direct children of a specified element.

ul > li {
  list-style-type: square;
}

8. Attribute Selector

The attribute selector selects elements based on the presence or value of an attribute.

input[type="text"] {
  border: 2px solid blue;
}

9. Pseudo-class Selector

Pseudo-classes define a special state of an element, such as hover or focus.

a:hover {
  color: red;
}

10. Pseudo-element Selector

Pseudo-elements style specific parts of an element.

p::first-letter {
  font-size: 24px;
  font-weight: bold;
}

Selector Priority (Specificity)

When multiple CSS rules target the same element, the browser decides which rule to apply based on specificity.

Why CSS Selectors Are Important

Tip: Use class selectors for most styling needs and avoid overusing ID selectors.