Syntax of CSS

There are two parts in the syntax of CSS. One is selector and the other is declaration block.

The Syntax of CSS

  • The selector is the HTML element which you want to style
  • The declaration part is divided into two part. They are property and value.
  • Multiple declarations are separated by colons and a declaration block is surrounded by curly braces.

Example:

selector {  property 1: value 1;   property 2: value 2;   property 3: value 3; }


Uses of CSS Selectors

Selectors are used for selecting the HTML element. Elements can be selected by their name of the element, attribute, class, id etc.

The element Selector

If the name of the element is used for selecting the element then it is element selector.

Example:

h1 {
  color: red;
  font-size: 24px;
}

Run Example

The id Selector

The id selector is used for the id attribute of the html. The id is the unique element of a document so the id selector is chosen for an unique element of the page.

An id selector is used after a # character in the stylesheet.

Example:

#id_name {
  background: blue;
  font-size: 24px;
}

Run Example

The class Selector

The class selector is used for the class attribute of the html. A class selector is used after a . (dot symbol) in the stylesheet.

Example:

.class_name {
  background: green;
  font-size: 24px;
}

Run Example

If you want to change a specific element under a class element then first you have to write the element name then the . character and class name.
The following example will change only the <h1> element under the class.

Example:

h1 .class_name {
  background: green;
  font-size: 24px;
}

Run Example

The Universal Selector

The universal selector is used to change the whole body style of a page. It selects all the elements of a page. It is specified by * charater.

Example:

* {
  font-family: arial;
  font-size: 24px;
}

Run Example

Group Selector

The group selector is used when multiple number of element in a document contain the same style.
Here is a example without using group selector:

Example:

h1 {
  font-family: arial;
  font-size: 24px;
}

h2 {
  font-family: arial;
  font-size: 24px;
}

p {
  font-family: arial;
  font-size: 24px;
}

Let's see the same example using group selector. In the group selector the elements are separated by a comma. It makes short your code.

Example:

h1, h2, p {
  font-family: arial;
  font-size: 24px;
}

Run Example