Using Basic CSS Selectors

Tutorial 1 of 5

Introduction

Goal of the Tutorial

This tutorial aims to give you a hands-on introduction to using basic CSS selectors. CSS selectors are the engine behind CSS - they determine how styles are applied to elements on a webpage.

Learning Outcome

By the end of this tutorial, you will have understood how to use type, class, and ID selectors in CSS, with the ability to target and style webpage elements using these foundational selectors.

Prerequisites

Basic knowledge of HTML and CSS is advised, but not strictly necessary.

Step-by-Step Guide

Understanding CSS Selectors

CSS selectors are used to "find" (or select) HTML elements based on their element name, id, class, attribute, and more.

The three basic selectors in CSS are:

  1. Type Selectors: These target elements by their node name.

  2. Class Selectors: These target elements by the class attribute. They're defined with a '.' followed by the class name.

  3. ID Selectors: These target elements by the id attribute. They're defined with a '#' followed by the id name.

Best Practices

  • Use type selectors for global styles.
  • Use class selectors when you want to style a group of elements.
  • Use ID selectors for unique elements.

Code Examples

Type Selector

/* This will style all the <h1> elements */
h1 {
  color: red;
}

Class Selector

/* This will style any element with class="intro" */
.intro {
  font-size: 20px;
}

ID Selector

/* This will style the element with id="first" */
#first {
  color: blue;
}

Summary

We've covered the basics of CSS selectors - the type, class, and id selectors. Remember:

  • Type selectors target by node name
  • Class selectors target by the class attribute
  • ID selectors target by the id attribute

For further learning, consider studying more advanced selectors like attribute selectors, pseudo-class selectors, and pseudo-element selectors.

Practice Exercises

  1. Exercise 1: Style all paragraphs (<p>) to have a font size of 18px.
  2. Exercise 2: Style any element with a class of .highlight to have a yellow background.
  3. Exercise 3: Style an element with an id of #main-title to be bold and underlined.

Solutions

  1. Solution 1:
p {
  font-size: 18px;
}
  1. Solution 2:
.highlight {
  background-color: yellow;
}
  1. Solution 3:
#main-title {
  font-weight: bold;
  text-decoration: underline;
}

Continue practicing with different HTML elements, classes, and ids to get a better grasp of CSS selectors. Happy styling!