CSS Syntax

CSS (Cascading Style Sheets) is the language used to style web pages. Understanding its css syntax is crucial for effective styling.

Basic Structure

A CSS rule-set consists of three main components:

  1. Selector: Specifies the HTML element(s) you want to style.
  2. Property: Defines the style attribute you want to modify (e.g., color, font-size, margin, etc.).
  3. Value: Sets the desired value for the property.

Syntax:

selector {
  property: value;
}

Example:

p {
  color: blue;
  font-size: 18px;
}

In this example:

  • p is the selector, targeting all paragraph elements.
  • color: blue; sets the text color of paragraphs to blue.
  • font-size: 18px; sets the font size of paragraphs to 18 pixels.

Key Components Explained

Selectors

Selectors determine which HTML elements the CSS rules will apply to. There are various types of selectors:

  • Element selectors: Target elements based on their tag name (e.g., p, h1, div).
  • Class selectors: Target elements with a specific class attribute (e.g., .my-class).
  • ID selectors: Target elements with a unique ID attribute (e.g., #my-id).
  • Attribute selectors: Target elements based on their attributes (e.g., a[href]).

Examples:

/* Element selector */
p {
  color: red;
}

/* Class selector */
.highlight {
  background-color: yellow;
}

/* ID selector */
#main-heading {
  font-size: 36px;
}

/* Attribute selector */
a[target="_blank"] {
  text-decoration: none;
}

Properties

Properties define the style attributes you can modify. Some common properties include:

  • color: Sets the text color.
  • font-size: Sets the font size.
  • background-color: Sets the background color.
  • margin: Sets the space outside an element.
  • padding: Sets the space inside an element.
  • border: Sets the border of an element.

Values

Values specify the desired value for a property. They can be keywords, numbers, lengths, colors, or other data types depending on the property.

Examples:

color: red;
font-size: 16px;
background-color: #f0f0f0;
margin: 20px;
padding: 10px;
border: 1px solid black;

Combining Rules

You can combine multiple rules within a single selector, separated by semicolons.

h1 {
  color: blue;
  text-align: center;
  font-size: 32px;
}

Comments

You can add comments to your CSS code using /* and */

/* This is a comment */
p {
  color: green; /* Comment within a rule */
}

Best Practices

  • Use consistent indentation for readability.
  • Organize your CSS into logical sections.
  • Use meaningful class and ID names.
  • Test your CSS in different browsers.
  • Consider using a CSS preprocessor for advanced features.

By understanding these fundamentals, you can effectively style your web pages and create visually appealing designs.

Share this Tutorials

CSS Syntax

Or copy link

CONTENTS
Scroll to Top