Basic Selectors

Learn the fundamentals of CSS selectors, and how to group and combine them effectively.

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;
}
Selecting elements using tag names

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>
Selecting elements using class attribute

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 element can have multiple classes.

ID

...

Create a free account to view this lesson.

By signing up, you agree to Educative's Terms of Service and Privacy Policy