CSS Selectors Tutorial

CSS selectors are used to target HTML elements and apply styles to them. They allow developers to select one or multiple elements in a webpage and define how they should appear.

Selectors are one of the most fundamental concepts in CSS because every CSS rule starts by selecting an element.

Without selectors, CSS would not know which HTML element should receive a particular style.

In this tutorial, we will learn the most commonly used CSS selectors with simple examples.

Basic CSS Selector Syntax

A CSS rule consists of a selector and a declaration block.

CSS
Basic CSS Syntax
selector {
  property: value;
}

The selector identifies the HTML element, and the declaration block contains the styles that will be applied.

1. Element Selector

The element selector selects HTML elements based on their tag name.

This selector will apply the same style to all elements of that type.

CSS
Element Selector Example
p {
  color: blue;
  font-size: 18px;
}

In this example, all paragraph elements will appear blue with a font size of 18 pixels.

2. Class Selector

The class selector targets elements with a specific class attribute.

Class selectors start with a dot symbol.

CSS
Class Selector Example
.highlight {
  background-color: yellow;
  font-weight: bold;
}
HTML
HTML Example
<p class="highlight">Important text</p>

Multiple elements can use the same class selector.

3. ID Selector

The ID selector is used to target a unique element on the webpage.

ID selectors start with the hash symbol.

CSS
ID Selector Example
#header {
  background-color: black;
  color: white;
}
HTML
HTML Example
<div id="header">Website Header</div>

Unlike classes, an ID should only be used once in a page.

4. Universal Selector

The universal selector selects all elements in the HTML document.

CSS
Universal Selector Example
* {
  margin: 0;
  padding: 0;
}

This selector is often used to reset browser default styles.

5. Group Selector

The group selector allows developers to apply the same styles to multiple elements.

CSS
Group Selector Example
h1, h2, h3 {
  color: darkblue;
}

This rule applies the same color to h1, h2, and h3 elements.

Best Practices for CSS Selectors

  • Use classes instead of IDs for reusable styles.
  • Keep selectors simple and readable.
  • Avoid unnecessary nesting.
  • Use meaningful class names.
  • Organize CSS rules properly.

Conclusion

CSS selectors are essential for styling web pages. They allow developers to target specific elements and control their appearance.

Understanding different selector types helps developers write clean and efficient CSS.

By mastering selectors, developers can build flexible and well-designed web interfaces.