• Discover
  • Collections
  • Board
  • Create
  • Profile
  • Settings
Paths

Lesson 1.2: CSS Selectors and Properties

Lesson 1.2: CSS Selectors and Properties

2 min read

Introduction

To style elements with CSS, you first need to tell CSS which HTML elements you want to style. This is where CSS selectors come into play. Once an element (or group of elements) is selected, you then apply various CSS properties to change its appearance. Understanding selectors and properties is fundamental to writing effective CSS.

Key Concepts

CSS Selectors

Selectors are patterns used to select the elements you want to style.

Common types include:

  • Type Selector: Selects all instances of a specific HTML tag (e.g., p selects all paragraphs).

  • Class Selector: Selects all elements with a specific class attribute (e.g., .highlight selects <span class="highlight">). This is very commonly used.

  • ID Selector: Selects a single element with a specific id attribute (e.g., #main-header selects <h1 id="main-header">). IDs should be unique per page.

  • Universal Selector: Selects all elements (*).

  • Attribute Selector: Selects elements with a specific attribute or attribute value (e.g., a[target="_blank"]).

CSS Properties and Values

Once an element is selected, you apply properties to it. A property defines what aspect of the element you want to style (e.g., color, font-size, background-color), and a value defines how that aspect should be styled (e.g., blue, 16px, #f0f0f0).

The general syntax is `selector { property:

value; }`.

Quick Example

Let's see how different selectors and properties work:

html
<p class="intro">This is an introductory paragraph.</p> <p>This is a regular paragraph.</p> <div id="main-content"> <h2 class="section-title">About Us</h2> </div> ```css p { /* Type selector */ font-family: 'Verdana', sans-serif; } .intro { /* Class selector */ color: navy; font-weight: bold; } #main-content { /* ID selector */ background-color: lightgray; padding: 20px; } .section-title { font-size: 2em; /* 2 times the root font size */ text-align: center; } ## Summary Selectors are crucial for targeting specific HTML elements, while properties and their values define the actual styles applied. Mastering type, class, and ID selectors, along with common styling properties, forms the core of styling web pages effectively. Always aim for specificity without over-complicating your selectors.
End of lesson
👏Well done!
Previous Lesson
Lesson 1.1: Introduction to CSS
Next Lesson
Lesson 1.3: The CSS Box Model

Course Content

0% Complete0/11 Lessons

Lesson 1.1: Introduction to CSS

Lesson 1.2: CSS Selectors and Properties

Lesson 1.3: The CSS Box Model

Quiz

Course Content

0% Complete0/11 Lessons

Lesson 1.1: Introduction to CSS

Lesson 1.2: CSS Selectors and Properties

Lesson 1.3: The CSS Box Model

Quiz