View video tutorial

CSS Syntax

CSS

Selectors and style declarations are what CSS syntax is all about.

CSS syntax


➔ CSS syntax consists of two parts selectors and style declarations.

➔ The function of selectors is to select the elements to which the CSS style will be applied.

➔ The function of the declaration part is to declare the CSS style inside curly braces that will be applied to the selected elements.

➔ A property and value pair inside curly braces separated by colons is called a CSS declaration, whereas multiple CSS declarations are separated by semicolons inside the same curly braces.

Apply CSS style using element/tag name.

Syntax

elementname {
    csspropertyname: propertyvalue;
}

Syntax

elementname {
    cssproperty1name: property1value;
    cssproperty2name: property2value;
}
Apply CSS style using element ID.
Syntax
#elementid {
    csspropertyname: propertyvalue;
}
Apply CSS style using element class name.
Syntax
.elementclass {
    csspropertyname: propertyvalue;
}
Apply CSS style on <p> and <h2> element.

Syntax

p, h2 {
    font-style: italic;
    color: white;
    background-color: gray;
  }

Example

<!DOCTYPE html>
<html>
<head>
    <title>CSS Syntax Example</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta charset="utf-8" />
    <style>
        div {
            background-color: #107080;
            color: white;
            padding: 20px;
        }
        p {
            padding: 10px 20px;
        }
    </style>
</head>
<body>
    <p>CSS Syntax Example</p>
    <div>
        <p>Selectors are used to select one or more HTML elements that we want to style.</p>
        <p>There are five categories of selectors that are used to select elements.</p>
    </div>
</body>
</html>
Try it Now »

Copy the code and click on the "Try it Now" button to see how it works.


Example

p {
  font-style: italic;
  color: red;
}
Try it Now »

Click on the "Try it Now" button to see how it works.


Explain Code

Here, p is a selector that selects the HTML elements to which you want to apply the style.

color is a CSS property and red is the property's value, font-style is a CSS property and italic is one of the property's values.

Curly braces { } are mandatory to enclose all CSS code.