CSS Syntax

CSS (Cascading Style Sheets) styles web pages. Understanding CSS syntax is crucial for effective styling. This page covers the basics: selectors, properties, values, and more.

Basic Structure

A CSS rule consists of a selector and a declaration block:


/* CSS Rule Set */
selector {
  property: value;
}

    

Selectors

Selectors target HTML elements to apply styles:

  • Element Selector: Targets tags (e.g., p, h1).
  • Class Selector: Targets classes (e.g., .class-name).
  • ID Selector: Targets unique IDs (e.g., #id-name).
  • Attribute Selector: Targets attributes (e.g., [type="text"]).
  • Group Selector: Styles multiple selectors (e.g., h1, h2).

Properties and Values

CSS properties define styles; values specify settings. For example:

/* Example CSS Rule */ p { color: blue; /* Property: color */ font-size: 16px; /* Property: font-size */ margin: 10px; /* Property: margin */ }

Comments

Use comments to annotate your code. They're ignored by browsers:

/* Single-line comment */ /* Multi-line comment spanning multiple lines. */

CSS Units

Common units in CSS:

  • Pixels (px): Fixed sizes (e.g., font-size: 16px;).
  • Percentages (%): Relative to containing element (e.g., width: 50%;).
  • Em and Rem: Based on font size (e.g., font-size: 1.5em;).

Inheritance and Specificity

CSS properties can be inherited from parent to child elements. Specificity determines which styles are applied when multiple rules match an element.