Skip to main content

CSS Syntax and Basic Rules

Understanding CSS syntax and basic rules is essential for writing and reading CSS code effectively. In this tutorial, you will learn the fundamentals of CSS syntax, along with sample code and simple explanations to help you get started with writing and understanding CSS code.

CSS syntax

A CSS rule consists of two parts: the selector and the declaration block. The selector targets HTML elements, and the declaration block contains one or more declarations, which are property-value pairs separated by a colon and enclosed in curly braces.


selector {
property: value;

Sample CSS rule:

p {
color: blue;
font-size: 16px;

In this example, the selector is p, targeting paragraph elements. The declaration block contains two declarations: color: blue; and font-size: 16px;.

CSS selectors

CSS selectors are used to target specific HTML elements and apply styles to them. There are several types of selectors, such as:

  • Element selectors: Target elements based on their HTML tag name (e.g., p, h1, div)
  • Class selectors: Target elements with a specific class attribute (e.g., .example-class)
  • ID selectors: Target an element with a specific ID attribute (e.g., #example-id)
  • Attribute selectors: Target elements with a specific attribute or attribute value (e.g., [data-example], [data-example="value"])


/* Element selector */
h1 {
color: red;

/* Class selector */
.example-class {
font-weight: bold;

/* ID selector */
#example-id {
font-size: 24px;

/* Attribute selector */
[data-example] {
background-color: yellow;

Combining and chaining selectors

You can combine and chain selectors to target elements more specifically or apply multiple styles at once.

  • Comma-separated selectors: Apply the same style to multiple selectors
  • Descendant selectors: Target elements that are descendants of another element
  • Child selectors: Target direct children of another element


/* Comma-separated selectors */
h3 {
font-family: Arial, sans-serif;

/* Descendant selector */
nav a {
text-decoration: none;

/* Child selector */
ul > li {
list-style-type: none;


In this tutorial, you learned the fundamentals of CSS syntax and basic rules, along with sample code and simple explanations. With this knowledge, you can now start writing and understanding CSS code, laying the foundation for more advanced CSS techniques and concepts.