Skip to main content

Basic CSS Selectors

Introduction

CSS selectors are the basic building blocks of CSS (Cascading Style Sheets). They define how to select HTML elements to apply styles. Understanding the different types of CSS selectors is fundamental to becoming proficient in web design. In this tutorial, we will discuss the most commonly used CSS selectors.

Basic CSS Selectors

CSS Selectors fall into several categories: element selectors, class selectors, id selectors, universal selectors, and group selectors. Let's take a closer look at each of these.

Element Selector

The element selector selects HTML elements based on the element name. For example, you can select all <p> elements in a document and set their color to red as shown below:

p {
color: red;
}

Class Selector

The class selector selects elements with a specific class attribute. It's denoted by a dot (.) followed by the class name. You can have multiple elements with the same class, allowing you to style multiple elements in the same way. For example:

.fancy-text {
color: blue;
font-size: 20px;
}

In the above example, all elements with the class fancy-text will have blue text and a font size of 20 pixels.

ID Selector

The ID selector selects an element with a specific id attribute. It's denoted by a hash (#) followed by the id name. Each id should be unique and only used once per page. For example:

#unique-text {
color: green;
}

In the above example, the element with the id unique-text will have green text.

Universal Selector

The universal selector, denoted by an asterisk (*), targets all elements on a page. It's generally used to apply broad styles or reset default styles. For example, you can use the universal selector to remove all margins and padding:

* {
margin: 0;
padding: 0;
}

Group Selector

If you want to apply the same styles to several different selectors, you can group them together by separating each selector with a comma. For example, if you want all <h1>, <h2>, and <h3> elements to have the color purple, you can write:

h1, h2, h3 {
color: purple;
}

Conclusion

Understanding and using CSS selectors effectively is crucial in designing and controlling the look and feel of a webpage. These basic selectors - element, class, id, universal, and group selectors - provide a solid foundation for styling your HTML elements. Keep practicing and experimenting with these selectors, and you'll get the hang of them in no time.

In the next tutorial, we'll delve deeper into more advanced CSS selectors. Stay tuned!