Lesson 4: CSS Basics: Selectors, Properties, and Values

In this lesson, we will cover the basics of CSS, focusing on selectors, properties, and values. The topics we will cover include:

Understanding CSS selectors

CSS selectors are used to target specific HTML elements on a page and apply styling to them. There are several types of selectors, including:

  • Element selectors: Target elements by their HTML tag name (e.g., p, h1, div)
  • Class selectors: Target elements by their class attribute value, using a period (.) followed by the class name (e.g., .example-class)
  • ID selectors: Target elements by their id attribute value, using a hash (#) followed by the ID name (e.g., #example-id)
  • Attribute selectors: Target elements based on the presence or value of a specific attribute (e.g., [href], [src^="https"])

Using CSS properties and values

CSS properties are used to define the appearance and layout of HTML elements. Each property has a specific value or a set of values that can be applied. For example:

p {
  color: red;
  font-size: 16px;
}

In this example, the color and font-size properties are used to style paragraph elements with a red text color and a font size of 16 pixels.

Some common CSS properties include:

  • color: Sets the text color
  • background-color: Sets the background color of an element
  • font-size: Sets the font size
  • font-family: Sets the font family
  • width and height: Set the width and height of an element
  • margin, padding, border: Control the spacing and borders around elements

Combining selectors, properties, and values in a CSS rule

A CSS rule consists of a selector, one or more property-value pairs, and a set of curly braces ({}). Property-value pairs are separated by a colon (:) and end with a semicolon (;). For example:

h1 {
  color: blue;
  font-family: Arial, sans-serif;
}

In this example, the h1 selector targets all <h1> elements on the page, and the property-value pairs define the text color and font family for those elements.

Actionable Work

  1. Create a new CSS file and practice writing some basic CSS selectors, such as element, class, ID, and attribute selectors.
  2. Add CSS properties and values to your selectors to style elements on a page.
  3. Link your CSS file to an HTML file using the <link> element in the <head> section.
  4. Experiment with different combinations of selectors, properties, and values to achieve different visual effects on your webpage.
  5. Preview your work in a web browser to see the effects of your CSS rules on the page’s appearance.