The web would be a very plain place without CSS. Every color, every font, every rounded corner, every column of a layout, and every smooth hover animation on the pages you use every day comes from CSS. It is the layer that turns a document into a design.
In this guide, you will learn what CSS is, how it works alongside HTML, how styles are written and applied, and the core concepts — selectors, the cascade, the box model, Flexbox, and responsive design — that everything else is built on.
What Is CSS?
CSS stands for Cascading Style Sheets. It is a style sheet language that tells the browser how to present a document written in a markup language such as HTML. Where HTML answers the question “what is this content?”, CSS answers “how should it look?”
A single CSS rule is small and readable. Here is one that makes every first-level heading on a page teal and twice the base font size:
h1 {
color: #0891b2;
font-size: 2rem;
}
Read it as a sentence: “For every h1 element, set the text color to
#0891b2 and the font size to 2rem.” The selector
h1 chooses the targets, and each line inside the braces sets one property.
CSS is maintained as a standard by the World Wide Web Consortium (W3C). Contrary to a common assumption, there is no “CSS version 4” or “CSS version 5”. After CSS3, the specification was split into dozens of independent modules — Selectors, Colors, Flexbox, Grid, and so on — each of which evolves at its own pace.
CSS is declarative. You describe the result you want, and the browser figures out how to produce it. That is why CSS feels very different from JavaScript, which gives the browser step-by-step instructions.
What CSS Does: Structure, Presentation, Behavior
Modern web pages are built from three layers. Each one has a distinct job, and keeping them separate is one of the oldest and most useful ideas in web development.
Structure
Headings, paragraphs, lists, images, links, and the meaning of the content. HTML describes what each piece of the page is.
Presentation
Colors, typography, spacing, borders, backgrounds, layout, and animation. CSS describes how the structure looks.
Behavior
Interactivity: responding to clicks, validating forms, fetching data, and updating the page without a reload.
This separation is not just tidy — it has practical benefits. The same stylesheet can style an entire website, so a change to a brand color happens in one place instead of a hundred. Styles can also be swapped out entirely: the same HTML can be presented as a desktop layout, a print layout, or a high-contrast accessible layout by changing the CSS.
A page with no CSS
If you strip the CSS from any website, you get exactly what the browser’s default stylesheet provides: black serif text on a white background, with headings slightly larger and links in blue with an underline. It is perfectly readable — and completely unremarkable. Everything beyond that baseline is CSS.
Think of a web page as a person. HTML is the skeleton and the organs. CSS is the skin, the clothing, and the posture. JavaScript is the nervous system that lets them move and react.
The Anatomy of a CSS Rule
Every CSS rule has the same shape. Once you can read one rule, you can read all of them.
A few details worth remembering:
- The selector comes first and is not wrapped in anything.
- The declaration block is always wrapped in curly braces
{ }. - Each declaration is a property, a colon, a value, and a semicolon.
- The semicolon is required between declarations — omitting it is one of the most common beginner errors.
- Whitespace and line breaks are ignored, so you can format rules however you like.
You can also write comments in CSS, which the browser ignores but humans find useful:
/* Card component styles */
.card {
padding: 16px; /* space inside the box */
border-radius: 8px;
background: #ffffff;
}
CSS only uses /* ... */ for comments. There is no // line
comment in standard CSS, and using one will break the rule that follows it.
The Three Ways to Add CSS to a Page
There are exactly three ways to connect CSS to HTML. All three work, but they are not equally good.
1. External stylesheet
The styles live in their own .css file, linked from the <head>
of the document:
<link rel="stylesheet" href="styles.css">
2. Internal stylesheet
The styles live inside a <style> block in the <head>:
<style>
h1 {
color: #0891b2;
}
</style>
3. Inline styles
The styles are written directly on a single element using the style
attribute:
<h1 style="color: #0891b2;">Styled heading</h1>
| Method | Reusable | Best for |
|---|---|---|
| External | Across every page on the site | Everything, in nearly every project |
| Internal | Only the page it lives in | Quick experiments and single-page demos |
| Inline | Only the element it is written on | Last-resort overrides and HTML emails |
In real projects, you will use an external stylesheet almost every time. It keeps your HTML clean, lets the browser cache the CSS once for the whole site, and makes a site-wide redesign a matter of editing one file.
Inline styles are hard to override, impossible to reuse, and they mix presentation back into your HTML — undoing the separation that makes CSS useful in the first place. Use them only when you have no other option.
CSS Selectors: Choosing What to Style
A selector is the part of a rule that decides which elements get styled. There are dozens of selectors in the specification, but a small handful covers most everyday work.
p— the element selector, matching every paragraph..card— the class selector, matching elements withclass="card".#header— the ID selector, matching the single element withid="header".*— the universal selector, matching everything.nav a— the descendant selector, matching links inside a nav.a:hover— the pseudo-class selector, matching a link while the pointer is over it.
Here is a page that uses several of them at once. The preview on the right is live — try hovering over the link.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Selectors</title>
<style>
body { font-family: system-ui, sans-serif; padding: 24px; background: #f8fafc; }
p { color: #334155; }
.highlight {
background: #fef3c7;
padding: 8px 12px;
border-radius: 8px;
}
#main-title { color: #0891b2; }
a:hover { color: #7c3aed; }
</style>
</head>
<body>
<h1 id="main-title">Selectors in action</h1>
<p>Every paragraph is styled by the element selector.</p>
<p class="highlight">This one also has a class applied.</p>
<p><a href="#">Hover over this link</a></p>
</body>
</html>
Notice how the class selector is reusable while the ID selector is unique. In practice, classes are the workhorse of CSS: they can be applied to as many elements as you like, which is exactly what you want for repeating components such as cards, buttons, and badges.
A class called .alert survives a redesign; one called .red-box
does not. Name classes after what the element is, not how it currently looks.
The Cascade, Specificity, and Inheritance
The “C” in CSS stands for cascading, and it answers a question that comes up constantly: when two rules both set the color of the same paragraph, which one wins?
The browser resolves conflicts using three considerations, in order:
- Importance and origin — rules marked
!importantand browser/user stylesheets are considered before normal author rules. - Specificity — a weight calculated from the selectors involved.
- Source order — if everything else is equal, the rule that appears later in the stylesheet wins.
How specificity is calculated
| Selector type | Example | Weight |
|---|---|---|
| Universal | * |
0,0,0,0 |
| Element / pseudo-element | h1, ::before |
0,0,0,1 |
| Class, attribute, pseudo-class | .card, [type="text"], :hover |
0,0,1,0 |
| ID | #header |
0,1,0,0 |
| Inline style | style="color: red" |
1,0,0,0 |
So #header beats .card, and .card beats
p — no matter what order they appear in. That is why an ID in a stylesheet
can be surprisingly difficult to override later.
Inheritance
Some properties, such as color and font-family, are
inherited: if you set them on body, every descendant element picks
them up automatically. Others, such as margin, padding, and
border, are not — each element starts with its own values.
Adding !important makes a declaration win against almost everything. It
feels like a quick fix, but it makes the cascade harder to reason about and usually
signals that your selectors need reorganizing instead.
The Box Model
Every element on a page — a heading, a paragraph, an image, a button — is rendered as a rectangular box. That box has four layers, and understanding them is the key to controlling spacing in CSS.
- Content — the text, image, or child elements themselves.
- Padding — space between the content and the border. It shares the element’s background.
- Border — a line drawn around the padding.
- Margin — space between this box and its neighbours. It is always transparent.
By default, the width you set applies only to the content box, so padding and
border are added on top of it. That surprises almost everyone the first time. The fix is a
single line, applied globally:
* {
box-sizing: border-box;
}
With box-sizing: border-box, padding and border are included inside the width
you specify, which makes layouts dramatically easier to reason about. Nearly every modern
project includes this rule.
Here is the box model in a real page:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Box Model</title>
<style>
body { font-family: system-ui, sans-serif; padding: 24px; background: #f8fafc; }
.card {
width: 260px;
padding: 24px;
border: 6px solid #0891b2;
margin: 16px;
background: #e0f7fa;
border-radius: 4px;
}
</style>
</head>
<body>
<div class="card">
Content box: 260px wide, plus padding, border, and margin.
</div>
</body>
</html>
In your browser’s developer tools, selecting an element shows a coloured box model diagram — orange for margin, green for padding, blue for the content area. It is the fastest way to find out where unwanted space is coming from.
What You Can Style: Common CSS Properties
The CSS specification defines hundreds of properties, but a small core group covers most of what you will write day to day.
Color & background
color, background-color, background-image, opacity
Typography
font-family, font-size, font-weight, line-height, text-align
Spacing
margin, padding, gap, width, height
Borders & shape
border, border-radius, box-shadow, outline
Layout
display, position, flex, grid-template-columns
Effects & motion
transform, transition, animation, filter
You do not need to memorize them. Every developer looks properties up constantly. What matters is knowing roughly what is possible, so you know what to search for when you need it.
Layout Basics: Flexbox and Grid
For years, laying out a page in CSS meant fighting with floats and tables. Modern CSS provides two purpose-built layout systems that solved the problem properly.
Flexbox — one dimension
Flexbox distributes items along a single axis, either a row or a column. It is ideal for navigation bars, toolbars, button groups, and centering anything.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Flexbox</title>
<style>
body { font-family: system-ui, sans-serif; padding: 24px; background: #f8fafc; }
.row {
display: flex;
gap: 12px;
justify-content: space-between;
}
.box {
flex: 1;
padding: 20px;
border-radius: 10px;
background: linear-gradient(135deg, #06b6d4, #7c3aed);
color: #ffffff;
text-align: center;
font-weight: 600;
}
</style>
</head>
<body>
<div class="row">
<div class="box">One</div>
<div class="box">Two</div>
<div class="box">Three</div>
</div>
</body>
</html>
Grid — two dimensions
CSS Grid lays items out in rows and columns at the same time. It is the right tool for page-level layouts, image galleries, and card grids. A single line is often enough:
.cards {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
gap: 16px;
}
That rule creates as many equal columns as will fit, wrapping to new rows automatically — a responsive card grid in three lines, with no media queries required.
If you are arranging items in a single line, reach for Flexbox. If you are defining a layout with rows and columns together, reach for Grid. They work happily side by side, and most real pages use both.
Responsive Design and Media Queries
People view websites on phones, tablets, laptops, and enormous desktop monitors. CSS lets you write rules that apply only when certain conditions are met, which is how one page can look right on all of them.
The first step is almost always the viewport meta tag in the <head>,
which tells mobile browsers to use the device’s real width instead of pretending to be a
desktop:
<meta name="viewport" content="width=device-width, initial-scale=1">
The second step is a media query — a block of CSS that only applies when the screen matches a condition:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Media Query</title>
<style>
body { font-family: system-ui, sans-serif; padding: 24px; margin: 0; background: #f8fafc; }
.banner {
background: #0f172a;
color: #ffffff;
padding: 24px;
border-radius: 12px;
text-align: center;
}
@media (min-width: 420px) {
.banner {
background: #0891b2;
padding: 40px;
font-size: 1.2rem;
}
}
</style>
</head>
<body>
<div class="banner">
Resize the preview — the styles change at 420px wide.
</div>
</body>
</html>
Resize the preview panel and you will see the banner change color and grow once the viewport is wider than 420 pixels. That is responsive design in its simplest form.
The mobile-first approach
Most developers write the mobile styles first as the default, then add
min-width media queries for larger screens. This keeps the base CSS simple
and means small devices download less unnecessary styling.
Prefer rem, em, %, and viewport units over fixed
pixels where you can. Relative units scale with the user’s font-size preference, which
is better for accessibility.
How to Debug CSS
CSS rarely fails with an error message. Instead, a style simply does not appear, and you have to work out why. Browser developer tools are how you do that.
- Open your page and press F12 (or right-click → Inspect).
- Use the element picker to select the element that looks wrong.
- Read the Styles panel — it lists every rule affecting that element, in cascade order.
- Rules that have been overridden are shown with a strikethrough.
- Check the Computed tab for the final resolved values.
- Edit properties live in the panel to test a fix before changing your file.
This workflow answers the three questions that account for most CSS bugs: Is my rule being applied at all? Is another rule overriding it? And where is this spacing coming from?
If none of your CSS is working, look at the Network tab. A wrong file
path or a missing rel="stylesheet" means the file never loaded, and no
amount of debugging selectors will help.
Common CSS Mistakes
These are the errors that trip up nearly every beginner. Recognizing them makes them much easier to fix.
1. Missing semicolons
h1 {
color: red
font-size: 2rem;
}h1 {
color: red;
font-size: 2rem;
}When a semicolon is missing, the browser tries to read the next line as part of the same value, and both declarations are discarded.
2. Confusing classes and IDs
/* HTML: class="card" */
#card { padding: 16px; }
/* HTML: id="header" */
.header { color: red; }/* HTML: class="card" */
.card { padding: 16px; }
/* HTML: id="header" */
#header { color: red; }3. Typos in property names
h1 {
colour: red;
font-weigth: bold;
}h1 {
color: red;
font-weight: bold;
}CSS silently ignores unknown properties. A typo means the declaration does nothing at all, with no warning.
4. Overusing !important
.card {
color: red !important;
}
.card {
color: blue !important;
}.card {
color: blue;
}5. Forgetting box-sizing
.box {
width: 300px;
padding: 24px;
border: 4px solid;
}
/* Renders at 356px wide */.box {
box-sizing: border-box;
width: 300px;
padding: 24px;
border: 4px solid;
}
/* Renders at 300px wide */6. Linking the stylesheet in the wrong place
<body>
<link rel="stylesheet" href="styles.css">
<h1>Hello</h1>
</body><head>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<h1>Hello</h1>
</body>7. Using pixels for everything
body { font-size: 16px; }
h1 { font-size: 32px; }body { font-size: 1rem; }
h1 { font-size: 2rem; }The W3C CSS Validation Service will flag typos, missing semicolons, and unknown properties. It is a fast way to catch the silent errors the browser will never tell you about.
CSS Best Practices
These habits keep a stylesheet readable as it grows from ten rules to a thousand.
Keep CSS in its own file
Link an external stylesheet from the head. Avoid inline styles except as a last resort.
Use meaningful class names
Name by purpose, not appearance: .alert rather than .red.
Set box-sizing globally
* { box-sizing: border-box; } prevents an entire category of sizing bugs.
Prefer relative units
Use rem, em, and % so layouts scale with user settings.
Keep specificity low
Favor single class selectors. Avoid IDs for styling and use !important sparingly.
Group and comment
Organize rules by component or section, with a short comment above each group.
Keep structure in HTML, presentation in an external CSS file, and specificity as low as you can get away with.
Frequently Asked Questions
1. What is CSS?
CSS stands for Cascading Style Sheets. It is the language that describes how HTML elements should be displayed — their colors, fonts, spacing, layout, and visual effects.
2. Is CSS a programming language?
No. CSS is a declarative style sheet language. It describes what the result should look like rather than giving the browser step-by-step instructions. It has no loops and no functions in the programming sense.
3. What is the difference between HTML and CSS?
HTML provides the structure and content of a page — headings, paragraphs, images, and links. CSS controls how that structure looks. HTML is the skeleton; CSS is the styling applied on top of it.
4. Do I need to learn HTML before CSS?
Yes. CSS selects and styles HTML elements, so you need a basic understanding of HTML tags, attributes, and document structure before CSS makes sense.
5. What does “cascading” mean in CSS?
It refers to how the browser decides which style wins when several rules target the same element. The cascade considers importance, origin, specificity, and source order.
6. What are the three ways to add CSS to a page?
An external stylesheet linked with the <link> element, an internal
<style> block in the head, and inline styles on individual elements
using the style attribute.
7. Which method of adding CSS should I use?
External stylesheets in almost every case. They are cached by the browser, reusable across many pages, and keep structure and presentation separate.
8. What is a CSS selector?
A selector is a pattern that tells the browser which elements a rule applies to.
Examples include p, .card, and #header.
9. What is specificity in CSS?
Specificity is a weight assigned to a selector that helps decide which rule wins when two rules set the same property on the same element. IDs beat classes, and classes beat element selectors.
10. What is the CSS box model?
Every element is a rectangular box made of four layers: content, padding, border, and margin. Understanding the box model is essential for spacing and layout.
11. What are Flexbox and Grid?
They are modern CSS layout modules. Flexbox lays out items along a single axis, while Grid handles two-dimensional layouts with rows and columns.
12. How do I center an element with CSS?
For horizontal centering, use margin: 0 auto on a block element that has
a set width. For full centering, make the parent a flex container with
justify-content: center and align-items: center.
Key Takeaways
- CSS stands for Cascading Style Sheets — it controls how HTML elements look.
- HTML provides structure, CSS provides presentation, and JavaScript provides behavior.
- A CSS rule is a selector plus a declaration block of property–value pairs.
- There are three ways to add CSS; external stylesheets are almost always the right choice.
- The cascade resolves conflicts using importance, specificity, and source order.
- IDs beat classes, and classes beat element selectors.
- Every element is a box made of content, padding, border, and margin.
box-sizing: border-boxmakes width calculations far more predictable.- Flexbox handles one-dimensional layout; Grid handles rows and columns together.
- Media queries and the viewport meta tag are what make a page responsive.
- Developer tools show you exactly which rules are applied and which are overridden.
- Keep specificity low, name classes by purpose, and prefer relative units.
What to Learn Next
Now that you know what CSS is and how it fits together, the next step is to practise the pieces you will use every day. Start with CSS Selectors Explained and The CSS Box Model for the two ideas that underpin everything else.
From there, explore CSS Colors and Backgrounds, CSS Typography, and CSS Units: px, em, and rem. When you are ready to build layouts, read CSS Flexbox Guide and CSS Grid Guide, then move on to Responsive Web Design.
Practice Challenge
The fastest way to make CSS click is to write a small amount of it by hand. This exercise takes about ten minutes and touches every core concept in this guide.
- Create a file called
index.htmland a file calledstyles.cssin the same folder. - In the HTML, add a
<link rel="stylesheet" href="styles.css">inside the<head>. - In the body, add a heading and a
divwithclass="card"containing a paragraph. - In the stylesheet, add
* { box-sizing: border-box; }at the top. - Give the card a
width,padding,border, andborder-radius. - Style the heading with a
colorand afont-sizeinrem. - Add a
:hoverrule that changes the card’s background color. - Add a media query with
min-width: 600pxthat increases the card’s padding. - Open the page, then open DevTools and inspect the card to see the box model diagram.
If you can complete those steps, you have written a stylesheet, used a class selector, set the box model correctly, added an interactive state, and made a responsive layout. That is a genuine first CSS project — and everything else you learn will build on it.