Basic Selectors
Explore the basics of CSS selectors to style web pages by targeting elements using element, class, and ID selectors. Understand how to combine and group selectors for efficient styling, and learn about specificity to control which styles apply when multiple rules target the same element.
In CSS, selectors are patterns used to select the elements we want to style. Understanding selectors is fundamental to controlling the look and feel of our web pages. The most common selectors are element selectors, class selectors, and ID selectors. Additionally, we can group and combine selectors to apply styles efficiently.
Element selectors
An element selector targets HTML elements by their tag name. This means we can apply styles to all instances of a specific element on our page.
p {color: blue;}
In this example, all <p> (paragraph) elements will have blue text. Element selectors are straightforward and useful when we want a consistent style for all elements of a particular type.
Class selectors
Class selectors allow us to target elements based on their class attribute. Classes are defined in our HTML elements using the class attribute and are prefixed with a dot . in CSS.
<style>.highlight {background-color: yellow;}</style><p class="highlight">This paragraph will be highlighted.</p>
Here, any element with class="highlight" will have a yellow background. Class selectors are versatile because multiple elements can share the same class, and an ...