CSS Syntax

CSS (Cascading Style Sheets) is the language used to style HTML documents. Understanding its CSS Syntax is crucial for designing visually appealing and user-friendly web pages.

CSS follows a simple rule-based syntax consisting of selectors, properties, and values. Each rule set is enclosed within curly braces {}.

CSS Syntax

Example:

selector {
    property: value;
}
CSS

Example with Styling:

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

Breakdown:

  • p → Selector (targets <p> elements)
  • color → Property (defines text color)
  • blue → Value (sets text color to blue)
  • font-size → Another property (sets font size)
  • 16px → Value (sets text size to 16 pixels)

Selectors define which HTML elements the styles apply to.

Targets all instances of an HTML element.

h1 {
    color: red;
}
CSS

Targets elements with a specific class.

.my-class {
    background-color: yellow;
}
CSS

Targets a unique element with a specific ID.

#my-id {
    font-weight: bold;
}
CSS

Targets multiple elements at once.

h1, h2, h3 {
    font-family: Arial, sans-serif;
}
CSS

Targets elements nested within another element.

div p {
    color: gray;
}
CSS

Comments are used to explain code and are ignored by browsers.

/* This is a comment */
CSS

Values in CSS can be expressed in different units:

  • Pixels (px): Fixed size (e.g., 16px)
  • Relative (em, %, rem): Responsive and scalable
  • Viewport (vw, vh): Based on screen size
<p style="color: blue; font-size: 16px;">Hello World</p>
HTML

<style>
p {
    color: blue;
}
</style>
HTML

<link rel="stylesheet" href="styles.css">
HTML

When multiple rules apply, CSS follows specificity:

  1. Inline styles (style="") – Highest priority
  2. ID Selectors (#id) – Higher specificity
  3. Class Selectors (.class) – Moderate specificity
  4. Element Selectors (h1, p) – Lower specificity

Use !important to force a style (use sparingly):

p {
    color: red !important;
}
CSS

Mastering CSS syntax is essential for web design. By understanding selectors, properties, values, and specificity, you can create stunning and responsive websites. Experiment with different CSS rules to improve your styling skills!