Premium CSS Course

CSS Syntax

CSS syntax is the foundation of writing CSS code to style HTML elements. Understanding how to correctly structure your CSS rules is key to applying styles effectively to web pages.

CSS Rule Structure

A CSS rule is made up of two main parts: the selector and the declaration block.


        selector {
            property: value;
        }
    

Here’s a breakdown of the structure:

Example of CSS Syntax

Here’s a simple CSS rule that changes the text color and font size of all <h1> elements:


        h1 {
            color: red;
            font-size: 36px;
        }
    

This rule targets all <h1> elements and sets their text color to red and font size to 36px.

Multiple CSS Declarations

A CSS rule can contain multiple declarations separated by a semicolon. Each declaration consists of a property and value pair.


        h1 {
            color: red;
            font-size: 36px;
            margin-bottom: 20px;
        }
    

This rule sets the color, font size, and margin of all <h1> elements at once.

Types of Selectors

CSS selectors are used to target HTML elements for styling. There are different types of selectors:

CSS Comments

You can add comments in your CSS code to explain your styles. Comments are ignored by the browser and do not affect the page rendering:


        /* This is a comment */
        h1 {
            color: red; /* This changes the color of h1 elements */
        }
    

Use comments to keep your code organized and easier to understand for you or other developers.

Best Practices for CSS Syntax

Example of CSS Syntax for a <div> Element

This example shows how to apply multiple CSS properties to a <div> element:


        div {
            background-color: #f4f4f4;
            padding: 20px;
            border: 2px solid #ccc;
            border-radius: 10px;
            width: 300px;
        }
    

This will apply a light gray background, 20px padding, a border, rounded corners, and set the width of the <div> element.