Getting everything ready for you…

Loading courses, problems and your progress. This takes just a moment.

0s

CSS Documentation

Style the web — selectors, the box model, Flexbox, Grid, animations and responsive design.

CSS (Cascading Style Sheets) controls how HTML looks — colours, fonts, spacing, layout, animations and how pages adapt to phones and big screens. HTML is the structure; CSS is the design.

1. Introduction & Setup

There are three ways to add CSS. An external stylesheet is the best for real projects:

<!-- index.html -->
<head>
  <link rel="stylesheet" href="styles.css" />          <!-- external (recommended) -->
  <style> h1 { color: tomato; } </style>               <!-- internal -->
</head>
<p style="color: gray;">Inline style (avoid)</p>
/* styles.css */
body {
  font-family: system-ui, sans-serif;
  margin: 0;
  background: #f6f7fb;
  color: #1f2333;
}

Output:

The page uses the system font, has no default margin,
a light grey background and dark text.

Use Chrome DevTools (F12 → Elements → Styles) to inspect and live-edit CSS.

⚠️ Common error: styles don't apply — check the href path, that the file is saved, and hard-refresh (Ctrl + Shift + R) to clear the cache.

2. Basic Syntax & Selectors

A rule = selector + declarations (property: value;).

p { color: #333; }                    /* element */
.card { padding: 16px; }              /* class */
#header { height: 64px; }             /* id */
nav a { text-decoration: none; }      /* descendant */
ul > li { list-style: square; }       /* direct child */
h2 + p { margin-top: 0; }             /* next sibling */
input[type="email"] { width: 100%; }  /* attribute */
a:hover { color: purple; }            /* pseudo-class */
li:nth-child(odd) { background: #eee; }
p::first-line { font-weight: bold; }  /* pseudo-element */
.btn::after { content: " →"; }
h1, h2, h3 { font-family: Georgia; }  /* group */
.card:has(img) { padding: 0; }        /* parent selector */

Specificity decides which rule wins when several match: inline style > #id > .class / [attr] / :pseudo-class > element. If equal, the later rule wins.

<p id="intro" class="lead">Which colour am I?</p>
<style>
  p { color: blue; }
  .lead { color: green; }
  #intro { color: red; }
</style>

Output:

"Which colour am I?" is red — #intro (id) has the highest specificity.

⚠️ Common error: fixing conflicts with !important everywhere. Lower your selector specificity (prefer classes) instead.

3. Colors, Units & Values

Colours: red, #7c5cff, #7c5cff80 (with alpha), rgb(124 92 255 / 0.5), hsl(255 100% 68%), currentColor, transparent.

Unit Meaning Use for
px pixel borders, small details
% relative to parent widths
em relative to the element's font-size padding that scales with text
rem relative to the root font-size (usually 16px) font sizes, spacing
vw / vh 1% of viewport width / height full-screen sections
fr fraction of free space grid columns
ch width of "0" readable line length (max-width: 65ch)
:root {
  --primary: #7c5cff;            /* custom property (variable) */
  --radius: 12px;
}
.button {
  background: var(--primary);
  border-radius: var(--radius);
  padding: 0.75rem 1.25rem;      /* 12px 20px with a 16px root */
  font-size: clamp(1rem, 2vw, 1.25rem);   /* min, preferred, max */
  width: calc(100% - 2rem);
  color: white;
}

Output:

A purple, rounded button whose text grows with the screen width
(between 16px and 20px) and is 2rem narrower than its container.

⚠️ Common error: writing margin: 10 without a unit — it's ignored. Only 0 can be unitless (and line-height).

4. The Box Model

Every element is a box: content → padding → border → margin.

* , *::before, *::after {
  box-sizing: border-box;     /* width includes padding + border (do this in every project) */
}
.box {
  width: 300px;
  padding: 20px;
  border: 2px solid #7c5cff;
  margin: 24px auto;          /* top/bottom 24px, centred horizontally */
}

Output:

With border-box:  the box is exactly 300px wide (content = 300 - 40 - 4 = 256px).
Without it:       the box would be 300 + 40 + 4 = 344px wide.
The box is centred because of margin: auto.

Shorthands: margin: 10px (all), 10px 20px (vertical, horizontal), 10px 20px 30px 40px (top, right, bottom, left — clockwise). Vertical margins between blocks collapse (the larger one wins).

⚠️ Common error: an element overflows its container after adding padding — you forgot box-sizing: border-box.

5. Display & Positioning

.inline   { display: inline; }        /* flows in text, ignores width/height */
.block    { display: block; }         /* new line, full width */
.ib       { display: inline-block; }  /* in-line but respects width/height */
.hidden   { display: none; }          /* removed from layout */

.parent   { position: relative; }     /* becomes the reference for absolute children */
.badge    { position: absolute; top: 8px; right: 8px; }
.navbar   { position: sticky; top: 0; z-index: 10; }   /* sticks while scrolling */
.chat-btn { position: fixed; bottom: 20px; right: 20px; } /* fixed to the viewport */

.center-me {                           /* classic centering with absolute */
  position: absolute;
  top: 50%; left: 50%;
  transform: translate(-50%, -50%);
}

Output:

.badge sits in the top-right corner of its .parent card.
.navbar stays at the top of the screen while you scroll.
.chat-btn always floats in the bottom-right corner.

⚠️ Common error: an absolute element jumps to the corner of the whole page — its parent needs position: relative.

6. Flexbox

Flexbox lays items out in one dimension (a row or a column).

.nav {
  display: flex;
  justify-content: space-between;  /* main axis: start | center | end | space-between | space-around */
  align-items: center;             /* cross axis: stretch | center | start | end */
  gap: 16px;
  flex-wrap: wrap;                 /* allow items to wrap onto new lines */
}
.nav .logo   { flex: 0 0 auto; }   /* don't grow or shrink */
.nav .search { flex: 1; }          /* take the remaining space */

.center {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;               /* perfectly centre a child on the screen */
}
.column { display: flex; flex-direction: column; gap: 8px; }
<nav class="nav">
  <span class="logo">Codify</span>
  <input class="search" placeholder="Search" />
  <button>Login</button>
</nav>

Output:

[Codify] [Search..........................................] [Login]
(logo left, search stretches to fill, button right, all vertically centred)

⚠️ Common error: justify-content doesn't work vertically in a column — in flex-direction: column the main axis is vertical, so swap the roles of justify-content and align-items.

7. Grid

Grid lays items out in two dimensions — rows and columns.

.gallery {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));  /* responsive without media queries */
  gap: 16px;
}

.layout {
  display: grid;
  grid-template-columns: 240px 1fr;
  grid-template-rows: auto 1fr auto;
  grid-template-areas:
    "header header"
    "sidebar main"
    "footer footer";
  min-height: 100vh;
}
.layout header  { grid-area: header; }
.layout aside   { grid-area: sidebar; }
.layout main    { grid-area: main; }
.layout footer  { grid-area: footer; }

.feature { grid-column: span 2; }   /* take two columns */

Output:

.gallery: as many 200px+ cards per row as fit (4 on a laptop, 1 on a phone).
.layout:
┌──────────── header ────────────┐
│ sidebar │         main          │
└──────────── footer ────────────┘

⚠️ Common error: using Grid when you only need a single row of items (use Flexbox), or Flexbox hacks for a 2-D layout (use Grid).

8. Responsive Design

  1. Add <meta name="viewport" content="width=device-width, initial-scale=1"> to the HTML.
  2. Write mobile-first CSS, then add min-width media queries for bigger screens.
  3. Use flexible units (%, rem, fr, clamp()) and max-width: 100% for images.
img { max-width: 100%; height: auto; }

.cards { display: grid; gap: 1rem; grid-template-columns: 1fr; }   /* phones: 1 column */

@media (min-width: 640px) {              /* tablets */
  .cards { grid-template-columns: repeat(2, 1fr); }
}
@media (min-width: 1024px) {             /* laptops */
  .cards { grid-template-columns: repeat(3, 1fr); }
}

@media (prefers-color-scheme: dark) {    /* follow the OS dark mode */
  body { background: #0b0d14; color: #e6e8f0; }
}
@media (prefers-reduced-motion: reduce) {
  * { animation: none !important; transition: none !important; }
}

.sidebar-card { container-type: inline-size; }
@container (min-width: 400px) {          /* container queries: style by parent width */
  .sidebar-card .title { font-size: 1.5rem; }
}

Output:

Phone (<640px):   1 card per row
Tablet (≥640px):  2 cards per row
Laptop (≥1024px): 3 cards per row
Dark mode OS:     dark background automatically

⚠️ Common error: the page looks zoomed-out on phones — the viewport meta tag is missing.

9. Animations & Transitions

.btn {
  background: #7c5cff;
  transition: transform 0.2s ease, background 0.2s ease;   /* animate changes */
}
.btn:hover {
  transform: translateY(-2px) scale(1.03);
  background: #6a4af0;
}

@keyframes pulse {                      /* multi-step animation */
  0%, 100% { transform: scale(1); opacity: 1; }
  50% { transform: scale(1.1); opacity: 0.7; }
}
.live-dot {
  width: 10px; height: 10px; border-radius: 50%;
  background: #22c55e;
  animation: pulse 1.5s ease-in-out infinite;
}

@keyframes spin { to { transform: rotate(360deg); } }
.loader {
  width: 32px; height: 32px;
  border: 3px solid #ddd; border-top-color: #7c5cff; border-radius: 50%;
  animation: spin 0.8s linear infinite;
}

Output:

.btn lifts up slightly and darkens smoothly on hover.
.live-dot is a green dot that gently pulses forever.
.loader is a spinning circular loading indicator.

Animate transform and opacity for smooth 60 fps animations — animating width, height, top or margin forces layout recalculation and can stutter.

⚠️ Common error: transition: all on many properties causes janky, unexpected animations. List the exact properties.

10. Advanced Concepts

The cascade order: importance (!important) → origin → specificity → order of appearance. @layer gives explicit control:

@layer reset, base, components;
@layer reset { * { margin: 0; } }
@layer components { .btn { padding: 8px 16px; } }

Pseudo-classes for state and structure: :focus-visible, :disabled, :checked, :invalid, :not(), :is(), :where() (zero specificity), :first-child, :last-child, :empty.

input:invalid:not(:placeholder-shown) { border-color: #ef4444; }
button:focus-visible { outline: 3px solid #7c5cff; outline-offset: 2px; }
:is(h1, h2, h3):hover { color: #7c5cff; }
.list > li:not(:last-child) { border-bottom: 1px solid #eee; }

Theming with variables (light/dark switch):

:root { --bg: #ffffff; --text: #111827; }
[data-theme="dark"] { --bg: #0b0d14; --text: #e6e8f0; }
body { background: var(--bg); color: var(--text); }

Native CSS nesting (supported in modern browsers):

.card {
  padding: 1rem;
  & h3 { margin: 0; }
  &:hover { box-shadow: 0 10px 30px rgb(0 0 0 / 0.15); }
}

Also learn: object-fit for images, aspect-ratio, scroll-behavior: smooth, scroll-snap, backdrop-filter, clip-path, logical properties (margin-inline), naming conventions like BEM (.card__title--active), and tools like Sass, PostCSS and Tailwind CSS.

11. Examples with Output

Example 1 — Card component

.card {
  max-width: 320px;
  padding: 1.25rem;
  border-radius: 16px;
  background: white;
  box-shadow: 0 8px 24px rgb(0 0 0 / 0.08);
  transition: transform 0.2s;
}
.card:hover { transform: translateY(-4px); }
.card img { width: 100%; aspect-ratio: 16 / 9; object-fit: cover; border-radius: 12px; }
.card h3 { margin: 0.75rem 0 0.25rem; }
A white rounded card with a soft shadow, a 16:9 cropped image on top,
a title below, and it lifts up a little when hovered.

Example 2 — Centre anything

.parent {
  display: grid;
  place-items: center;   /* shorthand for align-items + justify-items */
  height: 300px;
}
The child is centred horizontally and vertically inside a 300px-tall parent.

Example 3 — Responsive navbar

.nav { display: flex; align-items: center; gap: 1rem; padding: 1rem; }
.nav .links { display: none; }
@media (min-width: 768px) {
  .nav .links { display: flex; gap: 1.5rem; margin-left: auto; }
  .nav .menu-btn { display: none; }
}
Phone:  [Logo]                         [☰ menu button]
Laptop: [Logo]           Courses  Docs  Practice  Login

12. Practice Problems

  1. Style a blog article: readable font, max-width: 65ch, comfortable line-height, styled links and blockquotes.
  2. Build a pricing section with three cards using Flexbox; highlight the middle card.
  3. Recreate a photo gallery with CSS Grid that shows 1, 2 or 4 columns depending on screen width.
  4. Make a sticky navbar with a dropdown that opens on hover and on keyboard focus.
  5. Create a button set (primary, secondary, danger, disabled) with hover and focus-visible states.
  6. Add a light/dark theme using CSS variables and prefers-color-scheme.
  7. Build a loading spinner and a skeleton loader using @keyframes.
  8. Clone the layout of a website you like (header, sidebar, content, footer) using grid-template-areas.

13. Interview Questions

1. Explain the box model. Every element is content + padding + border + margin. With box-sizing: border-box, width includes padding and border.

2. What is specificity? The weight used to decide which rule applies: inline > id > class/attribute/pseudo-class > element. Equal specificity → the later rule wins.

3. Flexbox vs Grid? Flexbox is one-dimensional (a row or a column), great for components. Grid is two-dimensional (rows and columns), great for page layouts.

4. position values? static (default), relative (offset from itself, creates a reference), absolute (relative to the nearest positioned ancestor), fixed (to the viewport), sticky (relative until a scroll threshold, then fixed).

5. em vs rem? em is relative to the current element's font size (compounds when nested); rem is relative to the root html font size.

6. How do you centre a div? display: flex; justify-content: center; align-items: center; on the parent, or display: grid; place-items: center;, or margin: 0 auto for horizontal centring of a fixed-width block.

7. display: none vs visibility: hidden vs opacity: 0? none removes it from layout; visibility: hidden hides it but keeps its space; opacity: 0 keeps space and can still receive clicks.

8. What are pseudo-classes and pseudo-elements? Pseudo-classes select a state (:hover, :nth-child()); pseudo-elements style part of an element or add content (::before, ::after, ::first-line).

9. What is mobile-first design? Writing base styles for small screens, then adding min-width media queries for larger screens.

10. What is z-index and stacking context? z-index orders positioned elements on the z-axis, but only within the same stacking context (created by position + z-index, opacity < 1, transform, etc.).

14. Cheat Sheet & References

Selectors

/* element, class, id, descendant, child */
p {} .card {} #main {} nav a {} ul > li {}
a:hover {} input:focus-visible {} li:nth-child(2n) {} .btn::after {}
[type="email"] {} .card:has(img) {} :is(h1, h2) {}

Box model and spacing

* { box-sizing: border-box; }
margin: 0 auto; padding: 1rem 2rem; border: 1px solid #ddd; border-radius: 12px;
width: 100%; max-width: 1200px; min-height: 100vh;

Flexbox

display: flex; flex-direction: row | column; flex-wrap: wrap; gap: 1rem;
justify-content: center | space-between; align-items: center | stretch;
flex: 1; flex: 0 0 200px; align-self: flex-end; order: 2;

Grid

display: grid; grid-template-columns: repeat(3, 1fr); gap: 1rem;
grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
grid-column: span 2; grid-area: main; place-items: center;

Text and colour

font: 600 1rem/1.6 system-ui, sans-serif; color: #333; text-align: center;
text-transform: uppercase; letter-spacing: 0.05em; text-decoration: none;
background: linear-gradient(135deg, #7c5cff, #22d3ee); opacity: 0.8;
box-shadow: 0 4px 12px rgb(0 0 0 / 0.1);

Positioning and responsive

position: relative | absolute | fixed | sticky; top: 0; z-index: 10;
@media (min-width: 768px) { .grid { grid-template-columns: 1fr 1fr; } }
img { max-width: 100%; height: auto; }
font-size: clamp(1rem, 2.5vw, 2rem);

Transitions and animations

transition: transform 0.2s ease, opacity 0.2s;
transform: translateY(-4px) scale(1.05) rotate(5deg);
@keyframes fade { from { opacity: 0; } to { opacity: 1; } }
animation: fade 0.4s ease-out both;

Official documentation