Skip to content

CSS Tutorial

Official Documentation

This tutorial is based on MDN Web Docs. For the most up-to-date information, visit: https://developer.mozilla.org/en-US/docs/Web/CSS

Welcome to the comprehensive CSS tutorial! Learn how to style and design beautiful web pages.

What is CSS?

CSS (Cascading Style Sheets) is the language used to style and layout web pages. While HTML provides the structure and content of a webpage (like the skeleton and organs of a body), CSS is like the clothing, makeup, and accessories that make it look beautiful.

Think of it This Way

Imagine building a house:

  • HTML = The structure (walls, rooms, doors, windows)
  • CSS = The decoration (paint colors, furniture arrangement, curtains, lighting)
  • JavaScript = The functionality (electricity, plumbing, smart home features)

Without CSS, websites would look like plain text documents from the 1990s. CSS transforms boring content into engaging, visually appealing experiences.

What Can CSS Do?

CapabilityExamples
ColorsText color, background colors, gradients
LayoutPosition elements, create columns, center content
TypographyFonts, sizes, line spacing, text decoration
SpacingMargins, padding, gaps between elements
EffectsShadows, rounded corners, transparency
AnimationTransitions, keyframe animations, transforms
ResponsiveAdapt layouts for different screen sizes

Before and After CSS

html
<!-- Without CSS: Plain, unstyled HTML -->
<button>Click Me</button>

The button above would appear as a basic gray rectangle with default browser styling.

css
/* With CSS: Styled, attractive button */
.button {
    background-color: #007bff;    /* Blue background */
    color: white;                  /* White text */
    padding: 10px 20px;           /* Inner spacing */
    border: none;                  /* Remove default border */
    border-radius: 5px;           /* Rounded corners */
    font-size: 16px;              /* Text size */
    cursor: pointer;              /* Hand cursor on hover */
    transition: background 0.3s;  /* Smooth color change */
}

.button:hover {
    background-color: #0056b3;    /* Darker blue on hover */
}

The Power of CSS

With just a few lines of CSS, a plain button transforms into a professional, interactive element that users want to click!

Complete Example

css
/* Basic CSS Example */
body {
    font-family: Arial, sans-serif;  /* Set readable font */
    background-color: #f0f0f0;       /* Light gray background */
    margin: 0;                        /* Remove default margin */
    padding: 20px;                    /* Add some breathing room */
}

h1 {
    color: #333;           /* Dark gray text */
    text-align: center;    /* Center the heading */
    margin-bottom: 30px;   /* Space below heading */
}

.button {
    background-color: #007bff;
    color: white;
    padding: 10px 20px;
    border-radius: 5px;
}

Tutorial Structure

This tutorial is organized into three levels. Each level builds upon the previous one, so we recommend following the order if you're new to CSS.

Beginner Level

Start here if you're new to CSS. These fundamentals are essential for everything that follows.

ChapterTopicWhat You'll Learn
1BasicsSelectors, properties, values - the building blocks of CSS
2Colors & BackgroundsColor formats, gradients, background images
3TypographyFonts, text styling, readability

Intermediate Level

Once you're comfortable with the basics, learn how to control spacing and positioning.

ChapterTopicWhat You'll Learn
4Box ModelMargins, padding, borders - how elements take up space
5LayoutDisplay types, positioning, document flow
6FlexboxOne-dimensional layouts made easy

Advanced Level

Master modern CSS techniques used by professional developers.

ChapterTopicWhat You'll Learn
7GridTwo-dimensional layouts for complex designs
8Responsive DesignMedia queries, mobile-first approach
9AnimationsTransitions, keyframes, transforms
10Advanced TechniquesCSS variables, functions, best practices

Learning Path Recommendation

Don't skip ahead! CSS concepts build upon each other. Understanding the Box Model (Chapter 4) is essential before tackling Flexbox or Grid.

Prerequisites

Before starting this CSS tutorial, make sure you have:

RequirementWhy It's Needed
Basic HTML knowledgeCSS styles HTML elements - you need to understand tags, attributes, and document structure
Text editorVS Code is recommended (free, powerful, great CSS support)
Web browserChrome, Firefox, or Edge with developer tools for testing
CuriosityWillingness to experiment and break things!

New to HTML?

If you haven't learned HTML yet, we recommend completing our HTML Tutorial first. CSS and HTML work together, and trying to learn CSS without HTML is like trying to decorate a house that doesn't exist yet.

Getting Started

How CSS Connects to HTML

Think of HTML and CSS as a partnership:

  • HTML creates elements (a paragraph, a button, a heading)
  • CSS tells those elements how to look (blue text, rounded corners, centered)

CSS needs a way to "connect" to your HTML. There are three methods, each with different use cases:

Adding CSS to HTML

There are three ways to add CSS to your HTML:

1. Inline CSS

What it is: CSS written directly inside an HTML element using the style attribute.

html
<p style="color: blue; font-size: 16px;">Styled text</p>
ProsCons
Quick for testingHard to maintain
Highest specificityMixes content with presentation
No extra files neededCannot reuse styles

When to Use Inline CSS

Only use inline CSS for quick tests or when you need to override other styles. It's generally considered bad practice for production code.

2. Internal CSS (in <head>)

What it is: CSS written inside <style> tags in the HTML document's <head> section.

html
<!DOCTYPE html>
<html>
<head>
    <style>
        /* All paragraphs on this page will be blue */
        p {
            color: blue;
            font-size: 16px;
        }
    </style>
</head>
<body>
    <p>Styled text</p>
    <p>This paragraph is also blue!</p>
</body>
</html>
ProsCons
Styles multiple elements at onceOnly works for one HTML file
Good for single-page sitesCannot share styles between pages
No extra HTTP requestIncreases HTML file size

What it is: CSS written in a separate .css file and linked to HTML using the <link> tag.

html
<!-- index.html -->
<!DOCTYPE html>
<html>
<head>
    <!-- This line connects your CSS file -->
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <p>Styled text</p>
</body>
</html>
css
/* styles.css - A separate file */
p {
    color: blue;
    font-size: 16px;
}
ProsCons
Reusable across multiple pagesRequires additional HTTP request
Clean separation of concernsSlightly more setup
Browser caching improves performanceMust manage multiple files
Easier to maintain-

Best Practice

External CSS files are the industry standard for professional web development. They keep your code organized, maintainable, and allow browsers to cache styles for faster page loads.

Comparison Summary

MethodBest ForAvoid When
InlineQuick debugging, email templatesBuilding maintainable websites
InternalSingle-page sites, prototypesMulti-page websites
ExternalAll production websitesVery small one-off pages

CSS Syntax

Understanding CSS syntax is like learning the grammar of a new language. Once you know the rules, everything else becomes easier.

Anatomy of a CSS Rule

CSS rules consist of selectors and declarations:

css
selector {
    property: value;    /* This is a declaration */
    property: value;    /* Another declaration */
}

Visual Breakdown

css
/*  SELECTOR     DECLARATION BLOCK
    ↓            ↓                    */
    h1       {   color: blue;   }
/*               ↑       ↑
              PROPERTY  VALUE         */

Components Explained

ComponentDescriptionExample
SelectorTargets which HTML elements to styleh1, .button, #header
Declaration BlockContains all the style rules (inside { }){ color: blue; }
PropertyThe aspect you want to changecolor, font-size, margin
ValueThe setting for that propertyblue, 16px, 10px
DeclarationA complete property-value paircolor: blue;

Syntax Rules to Remember

css
/* Rule 1: Declarations end with semicolons */
p {
    color: blue;     /* ← Semicolon here */
    font-size: 16px; /* ← And here */
}

/* Rule 2: Properties and values are separated by colons */
h1 {
    color: red;      /* ← Colon between property and value */
}

/* Rule 3: Multiple selectors can share styles */
h1, h2, h3 {         /* ← Comma-separated selectors */
    font-family: Arial;
}

/* Rule 4: Comments use /* */ syntax */
/* This is a CSS comment - ignored by the browser */

Common Mistakes

css
/* WRONG - Missing semicolon */
p { color: blue }

/* WRONG - Using equals instead of colon */
p { color = blue; }

/* WRONG - Missing closing brace */
p { color: blue;

/* CORRECT */
p { color: blue; }

The Cascade

CSS stands for Cascading Style Sheets. But what does "cascading" mean?

The Waterfall Analogy

Imagine a waterfall flowing down a mountain. Water at the top flows down and can be "overwritten" by water joining from other streams below. CSS works similarly - styles "flow" down and can be overwritten by other rules.

What Happens When Multiple Rules Apply?

When multiple CSS rules target the same element, the browser needs to decide which one wins. This decision follows three main principles:

1. Specificity - The More Specific Rule Wins

Think of specificity like addressing a letter:

  • "Someone in the USA" (very general)
  • "Someone in New York" (more specific)
  • "John Smith at 123 Main St, New York" (very specific)

The more specific address always wins!

css
/* Specificity: 0-0-1 (just element) */
p { color: blue; }

/* Specificity: 0-1-1 (class + element) - WINS! */
p.intro { color: red; }

/* Specificity: 1-0-0 (ID) - WINS over classes! */
#special { color: green; }

Specificity Scoring

Selector TypeExampleScore
Elementp, div, h10-0-1
Class.button, .header0-1-0
ID#navbar, #main1-0-0
Inline stylestyle="..."1-0-0-0

Calculating Specificity

Count each type separately. div.container#main = 1 ID + 1 class + 1 element = 1-1-1

2. Source Order - Later Rules Override Earlier Ones

When two rules have the same specificity, the one that comes last wins:

css
p { color: blue; }   /* First */
p { color: red; }    /* Last - THIS WINS! */

3. Importance - The !important Override

!important overrides everything else (but use it sparingly!):

css
p { color: blue !important; }  /* This wins over everything */
p#special { color: red; }       /* Even this won't override */

Avoid !important

Using !important is like shouting in a conversation. It works, but it makes your code harder to maintain. Only use it as a last resort.

Cascade Priority (Highest to Lowest)

  1. !important declarations
  2. Inline styles (style="...")
  3. ID selectors (#id)
  4. Class selectors (.class)
  5. Element selectors (p, div)
  6. Universal selector (*)

Common CSS Properties Reference

Here are some frequently used CSS properties to get you started:

CategoryPropertyWhat It DoesExample
ColorcolorText colorcolor: #333;
background-colorBackground colorbackground-color: #f0f0f0;
Textfont-sizeText sizefont-size: 16px;
font-familyFont typefont-family: Arial;
text-alignText alignmenttext-align: center;
SpacingmarginOutside spacingmargin: 10px;
paddingInside spacingpadding: 20px;
SizewidthElement widthwidth: 100%;
heightElement heightheight: 200px;
BorderborderElement borderborder: 1px solid black;
border-radiusRounded cornersborder-radius: 5px;

Your First CSS Challenge

Try creating this simple styled card:

html
<!-- HTML -->
<div class="card">
    <h2>Hello CSS!</h2>
    <p>I'm learning to style web pages.</p>
</div>
css
/* CSS */
.card {
    background-color: white;
    border: 1px solid #ddd;
    border-radius: 8px;
    padding: 20px;
    max-width: 300px;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.card h2 {
    color: #333;
    margin-top: 0;
}

.card p {
    color: #666;
    line-height: 1.5;
}

Practice Makes Perfect

The best way to learn CSS is by experimenting. Change values, break things, and see what happens!

Video Tutorials

Recommended Video Resources

Learn CSS through these excellent video tutorials from the community.

Free Courses

CourseCreatorDescription
CSS Full CoursefreeCodeCamp11-hour comprehensive CSS course
CSS Crash CourseTraversy Media1-hour beginner crash course
CSS Tutorial for BeginnersDave Gray9-hour complete course
CSS in 100 SecondsFireshipQuick 100-second explanation

Official Resources

ResourceDescription
MDN CSS BasicsMozilla's official CSS learning path
CSS-TricksExcellent CSS tutorials and guides

Topic-Specific Videos

TopicVideoDuration
FlexboxFlexbox Tutorial~20 min
CSS GridCSS Grid Tutorial~18 min
AnimationsCSS Animations~30 min
Responsive DesignResponsive Web Design~1 hour

Next Steps

Ready to dive deeper? Start with Chapter 1: CSS Basics to learn about selectors, properties, and values in detail.

Let's begin your CSS journey!