Chapter 2: CSS Syntax and Selectors | WebLearner Pro

Chapter 2: CSS Syntax and Selectors

CSS (Cascading Style Sheets) syntax defines how CSS rules are written and how selectors are used to target HTML elements. In this chapter, we will cover the basic structure of CSS syntax and introduce you to common CSS selectors.

2.1 CSS Syntax Structure

CSS syntax follows a specific structure:

  • Selector: Specifies which HTML element the style will apply to.
  • Declaration Block: Contains one or more CSS declarations enclosed in curly braces { }.
  • Declaration: Consists of a property and value, separated by a colon :.

Example of CSS Syntax:


/* CSS Syntax Example */
h1 {
    color: #3498db;
    font-size: 24px;
}
    

2.2 Types of CSS Selectors

Selectors are used to select the HTML elements you want to style. There are several types of CSS selectors:

2.2.1 Universal Selector

The universal selector * targets all elements on the page.


/* Universal Selector Example */
* {
    margin: 0;
    padding: 0;
}
    

2.2.2 Element (Tag) Selector

The element selector targets HTML tags directly. For example, p will select all <p> elements.


/* Element Selector Example */
p {
    font-family: Arial, sans-serif;
}
    

2.2.3 Class Selector

The class selector is used to select elements with a specific class attribute. It starts with a period . followed by the class name.


/* Class Selector Example */
.button {
    background-color: #3498db;
    color: white;
}
    

2.2.4 ID Selector

The ID selector targets an element with a specific id attribute. It starts with a hash # followed by the ID name.


/* ID Selector Example */
#header {
    background-color: #333;
    color: white;
}
    

2.2.5 Descendant Selector

The descendant selector targets elements that are nested inside another element.


/* Descendant Selector Example */
nav ul li {
    display: inline;
    margin-right: 20px;
}
    

2.3 Combining Selectors

You can combine selectors to apply styles to multiple elements at once:


/* Combining Selectors Example */
h1, h2, h3 {
    font-family: 'Roboto', sans-serif;
    color: #333;
}
    

2.4 Specificity and Inheritance

CSS specificity determines which styles are applied when there are multiple conflicting styles for the same element. The more specific a selector is, the higher its priority. For example, ID selectors have higher specificity than class selectors.

2.5 Summary

In this chapter, you learned the basics of CSS syntax and various selectors. Understanding how to use selectors effectively will allow you to target HTML elements and style them appropriately. In the next chapter, we will explore CSS properties and values in more detail.