CSS Tutorial menu

CSS Syntax

Every piece of CSS is made of rules, and every rule follows the same simple pattern.

The Parts of a CSS Rule

Example

css
h1 {
  color: blue;
  font-size: 32px;
}
PartIn the exampleMeaning
Selectorh1Which HTML elements the rule styles
Declaration block{ ... }The curly brackets that hold the styles
Declarationcolor: blue;One style: a property and its value
PropertycolorWhat you want to change
ValueblueWhat you want to change it to

Read the rule above like a sentence: "For every h1, make the colour blue and the font size 32 pixels."

Writing Declarations Correctly

  • Put a colon : between the property and the value
  • End each declaration with a semicolon ;
  • Put all declarations inside curly brackets { }
  • You can write many declarations in one rule

Example

html
<!DOCTYPE html>
<html>
<head>
<style>
p {
  color: darkgreen;
  font-size: 18px;
  text-align: center;
  background-color: #e8f5e9;
}
</style>
</head>
<body>

<p>Admissions are open for the new batch.</p>
<p>Classes start on Monday.</p>

</body>
</html>
Try it Yourself »

Both paragraphs get the same style, because the selector p matches every paragraph on the page.

The semicolon after the last declaration is optional, but always add it. If you later add another line and forget the semicolon, your CSS will break.

Spaces and New Lines

The browser does not care about extra spaces or new lines. These two rules do exactly the same thing:

Example

css
h2 { color: purple; margin: 0; }

h2 {
  color: purple;
  margin: 0;
}

The second style, with one declaration per line, is much easier to read. Most developers use it.

CSS Comments

A comment is a note for humans. The browser ignores it. In CSS, a comment starts with /* and ends with */. It can be on one line or many lines.

Example

html
<!DOCTYPE html>
<html>
<head>
<style>
/* Main heading of the page */
h1 {
  color: #264de4;
}

/*
  Prices are shown in red
  so customers notice them
*/
.price {
  color: red;
  font-weight: bold;
}
</style>
</head>
<body>

<h1>School Bag</h1>
<p class="price">Rs 1,850</p>

</body>
</html>
Try it Yourself »

Comments are also handy for turning off a line while you test something: wrap it in /* */ and it stops working until you remove the comment marks.

Common Mistakes

MistakeWrongRight
Missing coloncolor red;color: red;
Missing semicoloncolor: red font-size: 20px;color: red; font-size: 20px;
Wrong bracketsp ( color: red; )p { color: red; }
Space in a value with a unitfont-size: 20 px;font-size: 20px;

If a declaration has a mistake, the browser skips just that one declaration and keeps the rest.

Exercise

Exercise

In the rule p { color: red; }, what is "color"?

Learn CSS with a teacher

Join the Web Development course at Workownix, online or in Orangi Town, Karachi, and get a certificate.

See the course Ask on WhatsApp