Module: CSS Basics

CSS syntax

CSS Syntax

CSS (Cascading Style Sheets) uses a specific syntax to define styles for HTML elements. Understanding this syntax is fundamental to writing effective CSS.

Basic Structure: Rule Set

A CSS rule set consists of a selector and a declaration block.

selector {
  property: value;
  property: value;
  ...
}
  • Selector: This identifies the HTML element(s) you want to style. Examples include p, h1, .my-class, #my-id.
  • Declaration Block: Enclosed in curly braces {}. Contains one or more declarations.
  • Declaration: Consists of a property and a value, separated by a colon :. Multiple declarations are separated by semicolons ;.

Example:

p {
  color: blue;
  font-size: 16px;
  line-height: 1.5;
}

This rule set targets all <p> (paragraph) elements and sets their text color to blue, font size to 16 pixels, and line height to 1.5.

Components Explained:

  • Property: The characteristic you want to change (e.g., color, font-size, background-color). CSS has a vast number of properties.
  • Value: The setting for the property (e.g., blue, 16px, #ffffff). Values can be keywords, lengths, colors, numbers, percentages, URLs, and more.
  • Colon (:): Separates the property from its value.
  • Semicolon (;): Separates each declaration within the declaration block. Crucial for correct parsing.
  • Curly Braces ({}): Enclose the declaration block.

Whitespace:

  • CSS is generally not sensitive to whitespace. You can use spaces, tabs, and newlines to improve readability. However, be consistent.
  • Whitespace within a value can sometimes be significant (e.g., in font-family values).

Comments:

You can add comments to your CSS code to explain what it does. Comments are ignored by the browser.

/* This is a single-line comment */

p {
  color: blue; /* Sets the text color to blue */
}

Case Sensitivity:

  • CSS is generally case-insensitive for property names and values (e.g., color is the same as Color).
  • However, selectors and attribute values are case-sensitive. It's best practice to use lowercase for everything to avoid potential issues.

Important Considerations:

  • Specificity: When multiple rules apply to the same element, the browser uses specificity rules to determine which style takes precedence. (This is a more advanced topic).
  • Cascading: Styles are applied in a cascading order, meaning styles from different sources (e.g., browser defaults, external stylesheets, inline styles) can overlap and interact. (Also a more advanced topic).