Basic CSS Syntax

CSS syntax consists of a set of rules that define how elements on the web page should be styled.

Watch the following video introduction to CSS syntax from the w3schools YouTube channel:

 

A CSS rule has two main parts:

  1. Selector: Defines which HTML elements the style will apply to.
  2. Declaration Block: Contains one or more declarations enclosed in curly braces {}.

Each declaration consists of a property and a value, separated by a colon :. Declarations are ended with a semicolon ;.

Here's the basic structure of a CSS rule:

selector {
  property: value;
  property: value;
}
Example:
h1 {
  color: blue;
  font-size: 24px;
}

example of css inside a style element with labels denoting the selector, property, value, comments, and the style element

Selectors

Selectors are like labels that tell your web page which parts to change with a certain style. For example, if you want to change the color of all headings, you use a selector to indicate that those heading elements should get the new color. There are different types of selectors, which will be covered in the next section.

For now, the only one you should remember is this one:

 

Properties and Values

CSS provides many properties to style elements, such as:

Example:
p {
  color: black;
  background-color: lightgray;
  padding: 10px;
  margin: 20px;
}

This rule styles all <p> (paragraph) elements with:

 

Comments in CSS

You can add comments in CSS to explain your code. Comments are ignored by the browser. Use /* to start a comment and */ to close it.

/* This is a comment */
h1 {
  color: blue; /* This is another comment */
}

 

Cascading in CSS

CSS stands for "Cascading Style Sheets," which means that styles can cascade, or fall in order, from parent to child elements. Styles applied to a parent element can affect child elements unless otherwise overridden.

 


 

Conclusion

CSS syntax is a combination of selectors and declarations. The selector tells which element to style, and the declaration tells how to style it using properties and values. As you learn more CSS, you’ll become more comfortable working with different types of selectors, properties, and the cascade to build beautiful web designs.