Syntax of CSS:

CSS syntax consists of a selector and a declaration block. Here’s a breakdown:

  1. Selectors:

    • Selectors are patterns used to select the HTML elements you want to style. They can target elements based on their tag name, class, ID, attributes, or even their relationship to other elements.
    css
     
    selector { property: value; }
    • Example: h1 selects all <h1> elements.
    • Example: .my-class selects all elements with class="my-class".
    • Example: #my-id selects the element with id="my-id".
  2. Declaration Block:

    • The declaration block contains one or more declarations separated by semicolons (;). Each declaration includes a property and a value.
    css
    selector { property1: value1; property2: value2; /* more properties and values */ }
    • Example:
    css
    h1 { color: blue; font-size: 24px; }
    • In this example, h1 is the selector, and color: blue; and font-size: 24px; are declarations.
  3. Properties and Values:

    • Properties are the aspects of the element you want to change (e.g., color, font-size, background-color).
    • Values specify how you want to style the property (e.g., blue, 24px, #FFFFFF).
  4. Comments:

    • CSS supports comments similar to those in JavaScript and HTML.
    css
    /* This is a CSS comment */

Example:

Consider the following HTML:

html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>My First CSS Example</title> <link rel="stylesheet" href="styles.css"> </head> <body> <h1>Hello, World!</h1> <p>This is a paragraph.</p> </body> </html>

And the accompanying styles.css file:

css
/* styles.css */ h1 { color: blue; font-size: 36px; } p { font-family: Arial, sans-serif; line-height: 1.6; }

In this example:

  • The h1 selector styles all <h1> elements to have blue text color and a font size of 36 pixels.
  • The p selector styles all <p> elements to use the Arial font (or a sans-serif fallback) and sets the line height to 1.6 times the font size.

CSS allows you to create visually appealing and consistent designs across your web pages by separating the content (HTML) from its presentation (CSS), making it easier to maintain and update your website's look and feel.