CSS Mastery

Learn CSS from selectors and the box model to responsive layouts, Flexbox, Grid, animations, and modern CSS.

CSS Basics

What is CSS?

CSS stands for Cascading Style Sheets. It controls the presentation, appearance, and layout of HTML documents.

HTML provides structure and meaning. CSS controls how that structure is displayed.

p {
  color: white;
  font-size: 20px;
}

Three Ways to Add CSS

External CSS

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

Internal CSS

<style>
  p {
    color: white;
  }
</style>

Inline CSS

<p style="color: white;">
  Hello
</p>

External stylesheets are generally preferred for maintainability and reuse.

CSS Mental Model

Selector
   ↓
Which elements?

Property
   ↓
What should change?

Value
   ↓
How should it change?
h1 {
  color: orange;
}

CSS Syntax

Basic Rule

selector {
  property: value;
  property: value;
}

Declaration

color: red;

A declaration consists of a property and its value.

Comments

/* This is a CSS comment */

p {
  color: white;
}

Multiple Selectors

h1,
h2,
h3 {
  color: white;
}

Selectors

Element Selector

p {
  color: white;
}

Class Selector

.card {
  padding: 20px;
}
<div class="card">
  Content
</div>

ID Selector

#header {
  background: black;
}

Universal Selector

* {
  box-sizing: border-box;
}

Attribute Selector

input[type="email"] {
  border: 1px solid gray;
}

Multiple Classes

.card.featured {
  border: 2px solid orange;
}
<div class="card featured">
  Featured card
</div>

Selector Groups

h1,
h2,
h3,
p {
  margin: 0;
}

Combinators

Descendant

article p {
  color: gray;
}

Selects paragraphs anywhere inside an article.

Child

article > p {
  color: gray;
}

Selects only direct child paragraphs.

Adjacent Sibling

h2 + p {
  margin-top: 0;
}

Selects a paragraph immediately following an h2.

General Sibling

h2 ~ p {
  color: gray;
}

Selects paragraphs appearing later among the siblings of an h2.

Specificity

What is Specificity?

When multiple CSS rules target the same element, specificity helps determine which declaration wins when other cascade conditions do not resolve the conflict.

General Specificity Order

Inline styles
     ↓
ID selectors
     ↓
Class / attribute / pseudo-class selectors
     ↓
Element / pseudo-element selectors

Example

p {
  color: white;
}

.text {
  color: yellow;
}

#intro {
  color: orange;
}

If the same element has id="intro" and class="text", the ID selector has greater specificity.

Specificity Advice

Keep selectors as simple as practical. Avoid building unnecessarily deep selectors that are difficult to override.

Cascade & Inheritance

The Cascade

CSS stands for Cascading Style Sheets because multiple style rules can interact. The browser resolves conflicts using the cascade.

Inheritance

Some properties are inherited from a parent element by default.

body {
  color: white;
  font-family: sans-serif;
}

Child elements can inherit these values unless their own rules override them.

Explicit Inheritance

button {
  color: inherit;
  font: inherit;
}

Important

.message {
  color: red !important;
}

!important changes the cascade priority. Use it sparingly.

Colors

Named Colors

color: red;
background-color: black;

Hexadecimal

color: #ff0000;
color: #00ff00;
color: #0000ff;

RGB

color: rgb(255, 0, 0);

RGBA

background: rgba(0, 0, 0, 0.5);

HSL

color: hsl(120, 100%, 50%);

Current Color

button {
  color: blue;
  border: 2px solid currentColor;
}

Units

Absolute Units

width: 300px;

Pixels are commonly used when a fixed dimension is appropriate.

Relative Font Units

font-size: 1rem;
font-size: 1.5em;

rem is relative to the root font size, while em is relative to the relevant inherited font size.

Viewport Units

width: 100vw;
height: 100vh;

Percentage

width: 50%;

Percentages are relative to an appropriate containing dimension or context.

Modern Viewport Units

min-height: 100svh;
min-height: 100lvh;
min-height: 100dvh;

Typography

Font Family

body {
  font-family: Arial, sans-serif;
}

Font Size

h1 {
  font-size: 3rem;
}

Font Weight

strong {
  font-weight: 700;
}

Line Height

p {
  line-height: 1.6;
}

Letter Spacing

h1 {
  letter-spacing: 0.05em;
}

Text Alignment

text-align: left;
text-align: center;
text-align: right;
text-align: justify;

Text Decoration

a {
  text-decoration: none;
}

Text Transform

text-transform: uppercase;

Box Model

Four Parts

┌─────────────────────────────┐
│           Margin            │
│  ┌───────────────────────┐  │
│  │        Border         │  │
│  │ ┌───────────────────┐ │  │
│  │ │      Padding      │ │  │
│  │ │ ┌───────────────┐ │ │  │
│  │ │ │    Content    │ │ │ │
│  │ │ └───────────────┘ │ │  │
│  │ └───────────────────┘ │  │
│  └───────────────────────┘  │
└─────────────────────────────┘

Width and Height

.box {
  width: 300px;
  height: 200px;
}

Padding

.box {
  padding: 20px;
}

Margin

.box {
  margin: 20px;
}

Border

.box {
  border: 1px solid black;
}

box-sizing

* {
  box-sizing: border-box;
}

With border-box, declared width and height include the padding and border.

Margin Shorthand

margin: 10px;
margin: 10px 20px;
margin: 10px 20px 30px;
margin: 10px 20px 30px 40px;

Display

Block

display: block;

The element participates in normal block layout and normally occupies available inline space.

Inline

display: inline;

Inline Block

display: inline-block;

None

display: none;

The element is removed from the layout.

Overflow

Hidden

overflow: hidden;

Auto

overflow: auto;

Scroll

overflow: scroll;

Axis Control

overflow-x: auto;
overflow-y: hidden;

Positioning

Static

position: static;

Relative

position: relative;
top: 10px;
left: 10px;

A relatively positioned element remains in normal flow while its visual position can be offset.

Absolute

.parent {
  position: relative;
}

.child {
  position: absolute;
  top: 0;
  right: 0;
}

An absolutely positioned element is positioned relative to an appropriate containing block.

Fixed

position: fixed;
bottom: 20px;
right: 20px;

Sticky

position: sticky;
top: 0;

Sticky positioning combines normal-flow behavior with offset-based positioning during scrolling.

z-index & Stacking

Basic z-index

.modal {
  position: fixed;
  z-index: 1000;
}

Stacking Context

z-index does not operate in a single global layer system. Certain CSS properties create stacking contexts that affect how descendants are composited.

Common Pattern

.header {
  position: sticky;
  top: 0;
  z-index: 10;
}

.modal {
  position: fixed;
  inset: 0;
  z-index: 1000;
}

Flexbox

What is Flexbox?

Flexbox is a one-dimensional layout system for arranging items along a primary axis and a cross axis.

Enable Flexbox

.container {
  display: flex;
}

flex-direction

flex-direction: row;
flex-direction: row-reverse;
flex-direction: column;
flex-direction: column-reverse;

justify-content

justify-content: flex-start;
justify-content: center;
justify-content: flex-end;
justify-content: space-between;
justify-content: space-around;
justify-content: space-evenly;

align-items

align-items: stretch;
align-items: flex-start;
align-items: center;
align-items: flex-end;

gap

.container {
  display: flex;
  gap: 20px;
}

flex-wrap

.container {
  display: flex;
  flex-wrap: wrap;
}

flex Property

.item {
  flex: 1;
}
.item {
  flex: 1 1 300px;
}

align-self

.special {
  align-self: flex-end;
}

Common Flexbox Layout

.nav {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 20px;
}

CSS Grid

What is Grid?

CSS Grid is a two-dimensional layout system for arranging content in rows and columns.

Enable Grid

.container {
  display: grid;
}

Columns

grid-template-columns: 200px 200px 200px;

Flexible Columns

grid-template-columns: 1fr 2fr;

Repeat

grid-template-columns: repeat(3, 1fr);

Gap

grid-gap: 20px;

Modern CSS generally uses the gap property.

gap: 20px;

Grid Rows

grid-template-rows: auto 1fr auto;

Grid Placement

.item {
  grid-column: 1 / 3;
  grid-row: 1 / 3;
}

Responsive Grid

.cards {
  display: grid;
  grid-template-columns:
    repeat(auto-fit, minmax(220px, 1fr));

  gap: 20px;
}

Grid Areas

.page {
  display: grid;

  grid-template-areas:
    "header header"
    "main sidebar"
    "footer footer";
}

.header {
  grid-area: header;
}

.main {
  grid-area: main;
}

.sidebar {
  grid-area: sidebar;
}

.footer {
  grid-area: footer;
}

Responsive Design

What is Responsive Design?

Responsive design allows a layout to adapt to different viewport sizes and devices.

Flexible Width

.container {
  width: min(100% - 32px, 1000px);
  margin-inline: auto;
}

Flexible Images

img {
  max-width: 100%;
  height: auto;
}

Mobile-First Layout

.cards {
  display: grid;
  grid-template-columns: 1fr;
}

@media (min-width: 700px) {
  .cards {
    grid-template-columns: repeat(2, 1fr);
  }
}

@media (min-width: 1000px) {
  .cards {
    grid-template-columns: repeat(3, 1fr);
  }
}

Media Queries

Basic Media Query

@media (max-width: 700px) {
  body {
    font-size: 16px;
  }
}

Minimum Width

@media (min-width: 700px) {
  .layout {
    display: grid;
  }
}

Orientation

@media (orientation: landscape) {
  .hero {
    min-height: 70vh;
  }
}

Reduced Motion

@media (prefers-reduced-motion: reduce) {
  * {
    animation-duration: 0s;
    transition-duration: 0s;
  }
}

Dark Mode Preference

@media (prefers-color-scheme: dark) {
  body {
    background: black;
    color: white;
  }
}

Pseudo-classes

Common Pseudo-classes

a:hover {
  color: green;
}

button:focus {
  outline: 2px solid blue;
}

input:focus-visible {
  outline: 2px solid orange;
}

input:checked {
  accent-color: green;
}

Structural Pseudo-classes

li:first-child {
  font-weight: bold;
}

li:last-child {
  margin-bottom: 0;
}

li:nth-child(2) {
  color: orange;
}

Negation

button:not(.primary) {
  background: gray;
}

Empty

.box:empty {
  display: none;
}

Pseudo-elements

::before

h2::before {
  content: "#";
  margin-right: 8px;
}

::after

a::after {
  content: " ↗";
}

::first-letter

p::first-letter {
  font-size: 2rem;
}

::first-line

p::first-line {
  font-weight: bold;
}

::selection

::selection {
  background: orange;
  color: black;
}

Form Styling

Basic Form Styling

input,
textarea,
select,
button {
  font: inherit;
}

Input Styling

input {
  width: 100%;
  padding: 10px 12px;
  border: 1px solid gray;
  border-radius: 5px;
}

Focus State

input:focus-visible {
  outline: 2px solid orange;
  outline-offset: 2px;
}

Disabled Controls

button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

Checkbox and Radio Accent

input[type="checkbox"],
input[type="radio"] {
  accent-color: green;
}

Backgrounds

Background Color

background-color: black;

Background Image

background-image: url("hero.jpg");

Background Size

background-size: cover;
background-size: contain;

Background Position

background-position: center;

Background Repeat

background-repeat: no-repeat;

Gradient

background: linear-gradient(
  90deg,
  black,
  gray
);

Borders & Shadows

Border

border: 1px solid black;

Border Radius

border-radius: 10px;

Individual Corners

border-top-left-radius: 10px;
border-top-right-radius: 10px;

Box Shadow

box-shadow:
  0 10px 30px rgba(0, 0, 0, 0.2);

Text Shadow

text-shadow:
  2px 2px 0 black;

Transforms

Translate

transform: translateX(20px);
transform: translateY(10px);
transform: translate(20px, 10px);

Scale

transform: scale(1.1);

Rotate

transform: rotate(45deg);

Skew

transform: skewX(10deg);

Transform Origin

transform-origin: center;

Transitions

Basic Transition

button {
  background: black;
  transition: background 200ms ease;
}

button:hover {
  background: gray;
}

Multiple Properties

button {
  transition:
    background 200ms ease,
    transform 200ms ease;
}

button:hover {
  transform: translateY(-2px);
}

Transition All

transition: all 200ms ease;

Explicitly naming properties is often easier to reason about than transitioning everything.

Animations

Keyframes

@keyframes fade-in {
  from {
    opacity: 0;
  }

  to {
    opacity: 1;
  }
}

Applying Animation

.box {
  animation:
    fade-in 500ms ease
    both;
}

Animation Properties

animation-name: fade-in;
animation-duration: 500ms;
animation-delay: 100ms;
animation-iteration-count: 2;
animation-direction: alternate;
animation-fill-mode: both;
animation-timing-function: ease;

Infinite Animation

animation-iteration-count: infinite;

Respect Reduced Motion

@media (prefers-reduced-motion: reduce) {
  * {
    animation: none !important;
    transition: none !important;
  }
}

CSS Variables

Custom Properties

:root {
  --primary: #00ffaa;
  --background: #333333;
  --text: #eeeeee;
}

Using Variables

body {
  background: var(--background);
  color: var(--text);
}

a {
  color: var(--primary);
}

Fallback Values

color: var(--text-color, white);

Local Variables

.card {
  --card-padding: 20px;

  padding: var(--card-padding);
}

Changing Variables by Context

.dark {
  --background: black;
  --text: white;
}

.light {
  --background: white;
  --text: black;
}

CSS Functions

calc()

width: calc(100% - 40px);

min()

width: min(100%, 1000px);

max()

width: max(300px, 50%);

clamp()

font-size: clamp(1.5rem, 4vw, 3rem);

clamp() provides a minimum, preferred, and maximum value.

minmax()

grid-template-columns:
  repeat(auto-fit, minmax(220px, 1fr));

Modern CSS

Logical Properties

margin-inline: auto;
padding-block: 20px;
padding-inline: 30px;

Logical properties describe layout in terms of writing direction rather than assuming a specific physical direction.

Aspect Ratio

.video {
  aspect-ratio: 16 / 9;
}

Object Fit

img {
  width: 100%;
  height: 300px;
  object-fit: cover;
}

Container Query

.card-wrapper {
  container-type: inline-size;
}

@container (min-width: 500px) {
  .card {
    display: grid;
    grid-template-columns: 1fr 1fr;
  }
}

:is()

:is(h1, h2, h3) {
  line-height: 1.2;
}

:where()

:where(h1, h2, h3) {
  margin-block: 0;
}

:where() is useful for grouping selectors while keeping their specificity very low.

:has()

.card:has(img) {
  padding-top: 0;
}

Common Mistakes

Using IDs Everywhere

#header {}
#main {}
#card {}
#button {}

Classes are usually more reusable and easier to compose.

Overusing !important

color: red !important;

Excessive use makes the cascade difficult to reason about and override.

Deep Selectors

body main section article div ul li a {
  color: red;
}

Prefer simpler selectors that directly express the component or state you need to style.

Fixed Width Everywhere

width: 1200px;

Fixed dimensions can create overflow and poor behavior on smaller screens. Prefer flexible sizing where appropriate.

Using Absolute Positioning for Main Layout

Flexbox and Grid should generally handle normal page layout. Absolute positioning is better suited to overlays and precisely positioned elements.

Ignoring Focus States

button:focus-visible {
  outline: 2px solid orange;
}

Keyboard users need a visible focus indicator.

Ignoring Reduced Motion

@media (prefers-reduced-motion: reduce) {
  * {
    animation: none;
    transition: none;
  }
}

Real Page Example

HTML + CSS Layout

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">

  <meta
    name="viewport"
    content="width=device-width, initial-scale=1.0"
  >

  <title>CSS Example</title>

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

<body>

  <header class="site-header">
    <h1>Developer Notes</h1>
  </header>

  <main class="layout">

    <section class="content">
      <h2>CSS Layout</h2>

      <div class="cards">

        <article class="card">
          <h3>Flexbox</h3>
          <p>One-dimensional layouts.</p>
        </article>

        <article class="card">
          <h3>Grid</h3>
          <p>Two-dimensional layouts.</p>
        </article>

      </div>
    </section>

    <aside class="sidebar">
      <h2>Resources</h2>
      <a href="#">Documentation</a>
    </aside>

  </main>

</body>

</html>

Matching CSS

* {
  box-sizing: border-box;
}

body {
  margin: 0;
}

.layout {
  width: min(100% - 32px, 1200px);
  margin-inline: auto;

  display: grid;
  grid-template-columns: 1fr 300px;

  gap: 30px;
}

.cards {
  display: grid;
  grid-template-columns:
    repeat(auto-fit, minmax(220px, 1fr));

  gap: 20px;
}

.card {
  padding: 20px;
  border: 1px solid gray;
}

@media (max-width: 800px) {
  .layout {
    grid-template-columns: 1fr;
  }
}

CSS Cheat Sheet

Selectors

p {}
.class {}
#id {}
* {}
[attr] {}
[attr="value"] {}
.parent .child {}
.parent > .child {}
h2 + p {}
h2 ~ p {}
button:hover {}
input:focus-visible {}
li:nth-child(2) {}
.card:has(img) {}

Box Model

width: 300px;
height: 200px;

margin: 20px;
padding: 20px;

border: 1px solid black;
border-radius: 10px;

box-sizing: border-box;

Typography

font-family: sans-serif;
font-size: 1rem;
font-weight: 600;
line-height: 1.5;
letter-spacing: 0.02em;
text-align: center;
text-decoration: none;
text-transform: uppercase;

Flexbox

display: flex;
flex-direction: row;
justify-content: center;
align-items: center;
flex-wrap: wrap;
gap: 20px;

flex: 1;
align-self: center;

Grid

display: grid;

grid-template-columns:
  repeat(3, 1fr);

grid-template-rows:
  auto 1fr;

gap: 20px;

grid-column: 1 / 3;
grid-row: 1 / 3;

Positioning

position: relative;
position: absolute;
position: fixed;
position: sticky;

top: 0;
right: 0;
bottom: 0;
left: 0;

z-index: 10;

Responsive CSS

@media (max-width: 700px) {
  ...
}

@media (min-width: 700px) {
  ...
}

@media (prefers-reduced-motion: reduce) {
  ...
}

Effects

transform: translateY(-2px);
transform: scale(1.05);

transition: transform 200ms ease;

box-shadow:
  0 10px 30px rgba(0, 0, 0, 0.2);

Functions

width: calc(100% - 40px);

width: min(100%, 1000px);

width: max(300px, 50%);

font-size:
  clamp(1.5rem, 4vw, 3rem);

grid-template-columns:
  repeat(auto-fit, minmax(220px, 1fr));

Learning Path

1. Learn CSS Syntax

Start with selectors, declarations, properties, values, comments, and basic rules.

2. Master Selectors

Learn classes, IDs, attributes, combinators, pseudo-classes, and pseudo-elements.

3. Understand the Cascade

Study inheritance, specificity, source order, and how conflicting rules are resolved.

4. Master the Box Model

Understand content, padding, border, margin, dimensions, and box-sizing.

5. Learn Typography

Practice fonts, sizes, weights, line height, spacing, alignment, and readable text layouts.

6. Learn Layout

Master normal flow, display modes, positioning, Flexbox, and Grid.

7. Learn Responsive Design

Build layouts that adapt naturally using flexible dimensions, Grid, Flexbox, and media queries.

8. Learn Visual Effects

Practice backgrounds, borders, shadows, transforms, transitions, and animations.

9. Learn Modern CSS

Add logical properties, functions, container queries, custom properties, and modern selector features to your toolkit.

10. Build Real Interfaces

Build navigation bars, cards, dashboards, forms, landing pages, article layouts, and responsive applications.

CSS Mastery Summary

The Core Mental Model

Selector
   ↓
Find the element

Cascade
   ↓
Decide which rule wins

Box Model
   ↓
Understand size and spacing

Layout
   ↓
Arrange elements

Responsive Design
   ↓
Adapt to different screens

Visual Effects
   ↓
Create interaction and polish

CSS Workflow

1. Start with semantic HTML
2. Establish box-sizing and base styles
3. Define typography
4. Build the main layout
5. Use Flexbox or Grid for components
6. Add responsive behavior
7. Add states such as hover and focus
8. Add transitions only where useful
9. Test keyboard accessibility
10. Test different viewport sizes
11. Simplify selectors and remove unnecessary rules

Essential Mental Model

HTML
Structure + Meaning

        ↓

CSS
Presentation + Layout

        ↓

JavaScript
Behavior + Interaction

What to Remember

  • Keep selectors simple and reusable.
  • Understand the cascade before increasing specificity.
  • Use the box model intentionally.
  • Use Flexbox for one-dimensional layouts.
  • Use Grid for two-dimensional layouts.
  • Prefer flexible layouts over unnecessary fixed dimensions.
  • Design responsive layouts from the beginning.
  • Keep keyboard focus visible.
  • Respect reduced-motion preferences.
  • Use modern CSS features when they simplify the problem.