The CSS Rule – The Basic Unit of CSS
Everything in CSS is built from rules. A rule has two parts:
- A selector — which element(s) to target
- A declaration block — what to do with them (wrapped in curly braces
{ })
selector {
property: value;
property: value;
}
A real example:
h1 {
color: #1572B6;
font-size: 2rem;
margin-bottom: 16px;
}
h1is the selector — targets all<h1>elements{ }is the declaration blockcolor,font-size,margin-bottomare properties#1572B6,2rem,16pxare values- Each
property: valuepair is a declaration and ends with a semicolon;
Every declaration must end with a semicolon ;. If you forget it, the browser ignores that declaration and the next one. The last declaration before the closing brace technically does not need a semicolon, but always include it — it prevents bugs when you add more declarations later.
CSS Selectors – Targeting the Right Elements
Selectors are patterns that tell CSS which HTML elements to style. There are five main types:
1. Element Selector (Type Selector)
Targets all instances of an HTML tag.
/* All <p> elements */
p {
color: #333;
line-height: 1.6;
}
/* All <h2> elements */
h2 {
font-size: 1.5rem;
border-bottom: 2px solid #1572B6;
}
2. Class Selector
Targets elements with a specific class attribute. Starts with a dot .
<p class="highlight">This text is highlighted.</p>
<p>This paragraph is not highlighted.</p>
<span class="highlight">Span also highlighted — classes are reusable.</span>
.highlight {
background-color: #fff3cd;
padding: 4px 8px;
border-radius: 3px;
font-weight: bold;
}
Classes are the most commonly used selector in real-world CSS. Elements can have multiple classes: class="highlight bold large".
3. ID Selector
Targets a single element with a unique id attribute. Starts with a hash #. IDs must be unique per page.
<header id="site-header">...</header>
#site-header {
background-color: #1572B6;
color: white;
padding: 16px 24px;
}
ID selectors have very high specificity — they override class and element selectors. Modern CSS best practices favor classes over IDs for styling (reserve IDs for JavaScript and anchor links).
4. Universal Selector
Targets every element on the page. Written as an asterisk *.
/* CSS reset — remove default browser spacing */
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
The box-sizing: border-box universal rule is one of the most common CSS "reset" techniques used in every professional project.
5. Attribute Selector
Targets elements with a specific attribute or attribute value.
/* All <input> elements with type="text" */
input[type="text"] {
border: 1px solid #ccc;
border-radius: 4px;
padding: 8px;
}
/* All <a> elements with an href starting with "https" */
a[href^="https"] {
color: green;
}
/* All images with an alt attribute */
img[alt] {
border: 2px solid transparent;
}
Grouping Selectors
Apply the same styles to multiple selectors by separating them with commas:
/* Instead of repeating yourself: */
h1 { margin-bottom: 16px; }
h2 { margin-bottom: 16px; }
h3 { margin-bottom: 16px; }
/* Do this: */
h1, h2, h3 {
margin-bottom: 16px;
font-family: 'Georgia', serif;
color: #111;
}
Descendant & Combinator Selectors
Target elements based on their relationship to other elements:
/* Descendant — any <a> inside a <nav> (no matter how deep) */
nav a {
text-decoration: none;
color: white;
}
/* Child — only direct <li> children of <ul> */
ul > li {
list-style: square;
}
/* Adjacent sibling — <p> immediately after <h2> */
h2 + p {
font-size: 1.1rem;
color: #555;
}
/* General sibling — all <p> siblings after <h2> */
h2 ~ p {
margin-top: 8px;
}
CSS Values – Colors, Sizes, and More
Every CSS property accepts specific types of values. Here are the most important:
Color Values
/* Named colors (147 available) */
color: red;
color: navy;
color: coral;
/* Hex codes — most common */
color: #ff0000; /* red */
color: #1572B6; /* CSS blue */
color: #fff; /* white (shorthand for #ffffff) */
/* RGB */
color: rgb(21, 114, 182);
/* RGBA — with transparency (0 = invisible, 1 = solid) */
color: rgba(21, 114, 182, 0.5);
/* HSL — hue (0-360°), saturation (%), lightness (%) */
color: hsl(207, 79%, 40%);
/* Modern: oklch — best for accessible color systems */
color: oklch(55% 0.18 240);
Length & Size Units
/* Absolute units */
width: 200px; /* pixels — most common for borders, shadows */
width: 2cm; /* centimetres — useful for print */
/* Relative to font size */
font-size: 1rem; /* 1rem = root font size (usually 16px) */
font-size: 1.5em; /* 1.5em = 1.5× the parent's font-size */
/* Relative to viewport */
width: 100vw; /* 100% of viewport width */
height: 100vh; /* 100% of viewport height */
font-size: 4vw; /* scales with screen width */
/* Percentage — relative to parent */
width: 50%; /* half the parent's width */
padding: 5%; /* 5% of parent's width */
Use rem for font sizes and most spacing — it stays consistent regardless of nesting depth. Use em when you deliberately want something to scale relative to the local font size (like padding on a button that should grow with its text). Use px for borders, shadows, and small fixed measurements.
CSS Comments
CSS comments use /* */ syntax. They are completely ignored by the browser:
/* ================================
Typography
================================ */
h1 {
font-size: 2rem; /* 32px at default browser settings */
color: #111;
}
/* TODO: update color to match new brand palette */
.btn {
background-color: #1572B6;
}
Comments can span multiple lines. There is no single-line comment syntax in CSS (unlike // in JavaScript).
CSS Shorthand Properties
Many CSS properties have shorthand versions that let you set multiple related properties in one declaration:
/* Longhand (verbose) */
margin-top: 16px;
margin-right: 8px;
margin-bottom: 16px;
margin-left: 8px;
/* Shorthand: top | right | bottom | left (clockwise) */
margin: 16px 8px 16px 8px;
/* Even shorter: top/bottom | left/right */
margin: 16px 8px;
/* Even shorter: all four equal */
margin: 16px;
/* Font shorthand */
/* font: style weight size/line-height family */
font: italic bold 1.2rem/1.6 Georgia, serif;
/* Background shorthand */
background: url('hero.jpg') center/cover no-repeat #1572B6;
/* Border shorthand: width style color */
border: 2px solid #1572B6;
CSS Syntax: Rules, Selectors, and How to Add It
A CSS rule has a selector (what to target) and a declaration block (how to style it, in property: value; pairs). Knowing the syntax and the three ways to include CSS avoids common beginner errors.
/* rule = selector + declaration block */
.card {
color: #333; /* declaration; the semicolon separates them */
padding: 1rem;
}
| Way to add CSS | Syntax | Use |
|---|---|---|
| External (best) | <link rel="stylesheet" href="..."> | reusable across pages |
| Internal | <style>...</style> in head | one-page styles |
| Inline | style="..." attribute | avoid — high specificity, not reusable |
Prefer external stylesheets: a linked .css file is cached by the browser, reused across every page, and keeps style separate from markup — the maintainable choice. Avoid inline styles (style="color:red") except for quick tests: they can't be reused, override almost everything (very high specificity, hard to override later), and mix structure with presentation. Syntax gotchas that break beginners: forget a semicolon between declarations and the next one is ignored; forget a closing } and the rest of the file silently fails; a typo in a property name means that line is skipped with no error (CSS fails quietly). Comments use /* */ only (no //). Because CSS errors are silent, when a style "doesn't work," check the selector actually matches and inspect the element in DevTools to see which rules won the cascade.
🏋️ Practical Exercise
- Write a rule selecting all
<p>elements. - Add two declarations (
colorandfont-size) to one rule. - Select an element by class with
.name. - Select an element by id with
#name. - Group two selectors with a comma.
🔥 Challenge Exercise
Write a small stylesheet using an element selector, a class selector, an id selector, and a grouped selector — each with at least two declarations. Confirm the syntax selector { property: value; } is correct and every declaration ends with a semicolon. Explain the parts of a CSS rule.
📋 Summary
- A CSS rule = selector + declaration block (
{ }). A declaration =property: value; - Main selectors: element (
h1), class (.name), ID (#name), universal (*), attribute ([attr]) - Group selectors with commas. Combine with descendant (space), child (
>), adjacent sibling (+), general sibling (~) - Colors: named, hex (
#RRGGBB),rgb(),rgba(),hsl() - Units:
px(fixed),rem/em(font-relative),%(parent-relative),vw/vh(viewport-relative) - Comments:
/* text */— ignored by the browser - Shorthand properties let you combine multiple declarations in one line
Interview Questions
- What are the parts of a CSS rule?
- What is the difference between a property and a value?
- How do you write a class selector vs an id selector?
- How do you apply one rule to multiple selectors?
- Why does each declaration end with a semicolon?
Related Topics
FAQ
The browser silently ignores the malformed declaration and the next one. There is no error message in the CSS itself (unlike JavaScript). If your CSS stops working mysteriously, check for missing semicolons. You can also use the browser DevTools (F12 → Styles panel) where invalid declarations are shown with a strikethrough.
Classes for almost everything. IDs are unique per page and have very high specificity, which makes them hard to override when you need to. Classes are reusable, composable (an element can have multiple classes), and have manageable specificity. Modern CSS architecture (BEM, utility-first) uses classes exclusively. Reserve IDs for JavaScript targets and anchor links.
px is an absolute pixel unit — always the same size regardless of context. em is relative to the font size of the parent element — if the parent font size is 16px, then 1.5em = 24px. rem is relative to the root font size (the <html> element, usually 16px) — it doesn't compound with nesting like em does. Use rem for consistent, accessible sizing; use em when you want local scaling; use px for small fixed values like borders.
margin is the space outside the element's border — it separates elements from each other. padding is the space inside the element's border — it separates content from the border. A simple way to remember: margin = outside (neighbors), padding = inside (breathing room). Background color and background images appear in the padding area but not in the margin area.
By default (box-sizing: content-box), when you set width: 200px, that is the width of the content only — padding and border are added on top, making the total element wider than 200px. With box-sizing: border-box, the 200px includes the padding and border — the total element stays 200px. This is much more intuitive for layout, which is why virtually every modern stylesheet starts with * { box-sizing: border-box; }.

