A CSS stylesheet includes a collection of rules that the web browser reads and applies to the elements like paragraphs, headings, etc., in the document.
A CSS rule has two main components: a selector and one or more declarations:
The selector identifies which element or elements in the HTML page the CSS rule affects.
Meanwhile, the declarations in the block define how the elements should appear on a webpage. Each declaration has a property and a value, separated by a colon (:
) and ending with a semicolon (;
), and the declaration blocks are enclosed by curly braces {}
.
The property is the style attribute you want to modify, such as font, color, background, etc. Each property has a value; for instance, the color property can be set to blue
or #0000FF
, among others.
To make CSS easier to read, you can place each declaration on a new line, like this:
h1 {
color: blue;
text-align: center;
}
In the example above, h1
is a selector, color
and text-align
are CSS properties, and blue
and center
are their respective values.
Note: A CSS declaration always ends with a semicolon ";
", and the declaration blocks are always surrounded by curly braces "{}
".
Comments are added to the source code to make it easier to understand. They help other developers (or your future self) to understand the purpose of the CSS. Comments are useful for programmers but ignored by browsers.
A CSS comment starts with /*
and ends with */
, as shown in the example below:
/* This is a CSS comment */
h1 {
color: blue;
text-align: center;
}
/* This is a multi-line CSS comment
that spans across more than one line */
p {
font-size: 18px;
text-transform: uppercase;
}
You can also comment out parts of your CSS code for debugging, like this:
h1 {
color: blue;
text-align: center;
}
/*
p {
font-size: 18px;
text-transform: uppercase;
}
*/
CSS property names and many values are not case-sensitive. However, CSS selectors are usually case-sensitive; for example, the class selector .maincontent
is different from .mainContent
.
To be safe, you should assume that all parts of CSS rules are case-sensitive.
You will learn about the different types of CSS selectors in the next chapter.