CSS Syntax

CSS (Cascading Style Sheets) is a powerful styling language used to control the presentation of HTML documents. In this tutorial, we will cover the basic syntax of CSS and how to apply styles to HTML elements.

CSS Rule Structure

A CSS rule consists of a selector and a declaration block. The selector targets the HTML element(s) to which the styles will be applied, and the declaration block contains one or more property-value pairs enclosed in curly braces.

Example
        
            selector {
  property1: value1;
  property2: value2;
}
        
    

Selectors

CSS selectors are used to target specific HTML elements. Here are some commonly used selectors


Properties and Values

CSS properties define the aspect of an element that you want to style, and values specify the specific styling for that property. Here are a few examples:

        
            element {
  color: blue;
  font-size: 24px;
  background-color: red;
  margin: 2px;
}
        
    

Cascading and Specificity:

CSS follows a cascading order of styles, where multiple rules can target the same element. The specificity of the selectors determines which styles take precedence. Inline styles have the highest specificity, followed by IDs, classes, and element selectors.

Comments:

CSS allows you to add comments to your code for documentation or explanation purposes.

        
            /* This is a single-line comment */

/*
This is a multi-line comment.
You can add multiple lines of comments here.
*/
        
    


Importing CSS

You can import external CSS files into your HTML document using the <link> element or the @import rule. This allows you to organize your CSS code into separate files for easier management.

Example
Try yourself
        
            <!DOCTYPE html>
<html>
  <head>
    <title>My Website</title>
    <link rel="stylesheet" href="styles.css">
  </head>
  <body>
    <h1>Welcome to my website!</h1>
    <p>This is some text.</p>
  </body>
</html>
        
    
Try yourself
        
            <!DOCTYPE html>
<html>
  <head>
    <title>My Website</title>
    <style>
      @import url('styles.css');
    </style>
  </head>
  <body>
    <h1>Welcome to my website!</h1>
    <p>This is some text.</p>
  </body>
</html>