CSS Syntax

You'll learn how to add CSS rules to your stylesheet in this article.


Understanding CSS Syntax

A CSS stylesheet consists of a set of rules that the web browser interprets and applies to different elements of a document, such as paragraphs and headers.

The primary parts of a CSS rule are the selector and one or more declarations:

CSS Syntax

The selector determines which HTML elements the CSS rule should be applied to.

Declarations control the formatting of elements on a webpage. They are enclosed in curly brackets and each declaration consists of a property and a value separated by a colon and terminated with a (;) semicolon.

The property represents the style attribute to be modified, such as font, color, or background. Each property has a corresponding value, such as blue or #0000FF for the color property.

h1 {color:blue; text-align:center;}

To enhance readability, it is recommended to write each declaration on a separate line.

<style>  
h4 {
    color: purple;
    text-align: left;
}
</style>

In the given example, "h1" is a selector, "color" and "text-align" are CSS properties, and "blue" and "center" are the values assigned to those properties.

A CSS declaration must always end with a semicolon ";", and declaration groups must be enclosed in curly brackets "{}".


Writing Comments in CSS

Comments can be added to CSS code to improve its understandability for developers. Browsers ignore comments, but they serve as important notes for programmers.

As illustrated in the example below, a CSS comment starts with /* and finishes with */ :

<style>
/* This is a CSS comment */
/* Comments are not displayed,
    by the browser */
h4 {
    color: blue;
    text-align: center;
}
</style>

During development, it can be useful to leave some CSS code uncommented for debugging purposes.

<style>
h1 {
    color: green;
    text-align: left;
}
/*
p {
    font-size: 19px;
    text-transform: uppercase;
}
*/
</style>

Case Sensitivity in CSS

The names of CSS properties and many of their values are not case-sensitive. The class selector.maincontent is not the same as .mainContent, despite the fact that CSS selectors are normally case-sensitive.

As a result, you should presume that all components of CSS rules are case-sensitive to be on the safe side.