CSS Syntax

CSS syntax is used to add CSS to an HTML document. A CSS syntax consists of a selector and a declaration block. For example,

selector {
    property1: value;
    property2: value;
}

The basic syntax of CSS includes 3 main parts:

  • selector - specifies the HTML element that we want to apply the styles
  • property1 / property2- specifies the attribute of HTML elements that we want to change (color, background, and so on)
  • value - specifies the new value you want to assign to the property (color of the text to the red, background to gray, and so on)
CSS Syntax Description Image
Basic Syntax Description

Example CSS Syntax

Let us see an example of CSS

p {
    color: red;
    font-size: 20px;
    background-color: yellow;
}

Here,

  • p - selector that selects all the <p> elements from the document
  • color: red; - changes the text color of <p> contents to red
  • font-size: 20px; - changes the font size of <p> contents to 20px
  • background-color: yellow; - sets the background of the <p> element to yellow

We add CSS to an HTML file using <style> tag. For example,

<html lang="en">

<head>
    <link rel="stylesheet" href="style.css" />
    <title>Browser</title>

<style> p { color: red; font-size: 20px; background-color: yellow; } </style>
</head> <body> <p>This is a paragraph</p> </body> </html>

Browser Output:

Browser Output produced by the code above

Example: Styling Multiple Elements

We can apply CSS to multiple HTML elements at once. For example,

h1, p
{ color: red; font-size: 20px; background-color: yellow; }

Here, the CSS rules will be applied to both the <h1> and <p> elements. Now, let's add the above CSS code to our HTML file.

<html lang="en">

<head>
    <link rel="stylesheet" href="style.css" />
    <title>Browser</title>

    <style>
h1,p { color: red; font-size: 20px; background-color: yellow; }
</style> </head> <body> <h1>This is the heading</h1> <p>This is a paragraph</p> <div>This is a div</div> </body> </html>

Browser Output

Browser output produced by the code above

CSS Syntax for Inline CSS

We can apply CSS to a single HTML element using the style attribute within the HTML tag. This is called inline CSS. For example,

<p style="color: blue">This text will be blue.</p>

Browser Output

A simple page with a paragraph

Here,

style="color: blue"
changes the text color of the paragraph to blue.

Multiple Properties in Inline CSS

We can also add multiple styling using inline CSS. For example,

<p style="color: blue; font-size: 50px">This text will be blue.</p>

Browser output

Browser output with a paragraph element.

Here, we have used multiple properties by separating them with a (;) semicolon.

Style Attribute syntax description

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges