D DevBrainBox

CSS Syntax and Rules

CSS

CSS Syntax & Rules:

CSS (Cascading Style Sheets) defines the visual appearance of HTML elements on a webpage.

CSS syntax consists of two main parts:

selector {
    property: value;
}
  • Selector: Identifies the HTML element(s) to be styled.
  • Property: Specifies the feature to style (e.g., color, font-size, margin).
  • Value: Defines the value assigned to the property (e.g., red, 16px, 10%).

How to Write CSS:

CSS rules follow a structured format:

h1 {
    color: blue;
    font-size: 24px;
    margin-bottom: 20px;
}

Here:

  • h1 is the selector (targets all <h1> elements).
  • color, font-size, and margin-bottom are properties.
  • blue, 24px, and 20px are respective values. Each CSS declaration ends with a semicolon (;).

Types of Selectors:

Selectors help you pinpoint which HTML elements to style.

TypeExampleExplanation
Elementp {}Selects all paragraphs (<p>).
Class.className {}Selects elements with a specific class (class="className").
ID#uniqueId {}Selects one element with a unique ID (id="uniqueId").
Universal* {}Selects all elements on the page.
Attributeinput[type="text"] {}Selects elements by attribute and value.
Pseudo-classa:hover {}Selects elements based on their state or user interaction.

Types of CSS

CSS can be applied in three ways:

Inline CSS (inside HTML elements)

<p style="color:blue;">Inline styled text.</p>

Internal CSS (inside HTML <style> tags)

<head>
  <style>
    h1 { color: green; }
  </style>
</head>

External CSS (separate .css file)

 style.css
body {
  background-color: white;
}

In HTML:

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

Basic CSS Syntax Rules:

  • Curly braces contain declarations.
  • Declarations end with a semicolon (;).
  • Multiple selectors can be combined with a comma (,):

Commenting in CSS

Comments explain or disable parts of your CSS.

/* This is a comment, ignored by browser */

/* .hidden {
    display: none;
} */

On this page