Skip to content
Qyubie Learn
Web Development courseLesson 3 of 20 · tap to see all lessons

Web Development · Beginner

CSS Fundamentals: Selectors, Colors, Typography, the Box Model, Flexbox, Grid, and Responsive Design

Style web pages with CSS: selectors, colors, fonts, backgrounds, the box model, Flexbox and Grid layouts, and media queries for phones and desktops.

  • Qyubie Learn Editorial Team
  • Published
  • 17 min read

Includes 2 exercises and 2 quick checks you can do right here.

HTML says what is on the page; CSS (Cascading Style Sheets) says how it looks: colors, fonts, spacing, and where things sit on the screen. The same HTML can look like a plain document or a polished app, depending only on the CSS. This lesson covers the CSS you'll use in every project, including when you switch to Tailwind CSS in lesson 14.

By the end of this lesson you will be able to:

  • write CSS rules and add CSS to a page three ways,
  • select elements by tag, class, ID, and relationship,
  • style colors, text, and backgrounds,
  • explain the box model: content, padding, border, and margin, and
  • lay out a page with Flexbox and Grid, and make it responsive with media queries.

Rules, properties, and values

A CSS rule has a selector (which elements) and declarations (what to change):

h1 {
  color: navy;
  font-size: 32px;
}
  • h1 is the selector.
  • color: navy; is a declaration: a property, a colon, a value, and a semicolon.
  • The declarations go between curly braces.

There are three ways to add CSS:

<!-- 1. External file: best for real sites, shared by every page -->
<link rel="stylesheet" href="style.css">

<!-- 2. Internal: a <style> block in the <head> of one page -->
<style>
  h1 { color: navy; }
</style>

<!-- 3. Inline: on a single element (avoid; hard to maintain) -->
<h1 style="color: navy;">Hello</h1>

Use an external stylesheet for real projects: change one file and every page updates. The examples here use <style> blocks so each one fits in a single box.

Selectors

Try it · HTML & CSS

Preview (index.html, updates as you type)
SelectorSelectsExample
pevery element of that typep { }
.nameevery element with class="name".note { }
#namethe one element with id="name"#main-title { }
A BB anywhere inside Anav a { }
A > BB directly inside Aul > li { }
A, Bboth A and Bh2, h3 { }
:hover, :focus, :first-childelements in a state or positiona:hover { }

Prefer classes for styling. An element can have several (class="card featured"), and many elements can share one. IDs must be unique on a page, so save them for anchors and JavaScript.

The cascade and specificity

When two rules set the same property on the same element, which wins?

  1. The more specific selector wins: an ID beats a class, and a class beats a tag. Inline styles beat all three.
  2. If they're equally specific, the rule that comes later wins.

Try it · HTML & CSS

Preview (index.html, updates as you type)

Some properties, such as color and font-family, are inherited: set them on body, and all the text inside gets them.

Quick check

Given #intro { color: red; } and .lead { color: green; }, what color is <p id="intro" class="lead">?

Colors, typography, and backgrounds

Try it · HTML & CSS

Preview (index.html, updates as you type)

Colors can be written as names (navy), hex (#211470), rgb(33, 20, 112), or hsl(...). Add transparency with rgb(0 0 0 / 50%) or an 8-digit hex. Keep enough contrast between text and background so everyone can read it.

Units:

UnitRelative toGood for
pxfixed pixelsborders, small details
remthe root (html) font size, usually 16pxfont sizes, spacing
emthe element's own font sizespacing that scales with its text
%the parent's sizewidths
vw / vh1% of the viewport width / heightfull-screen sections

Using rem for text means the page respects a user who sets a larger default font size in their browser.

The box model

Every element is a rectangular box with four layers, from inside out:

┌─────────────── margin (space outside, transparent) ───────────────┐
│ ┌──────────── border ─────────────────────────────────────────┐   │
│ │ ┌───────── padding (space inside, takes the background) ──┐ │   │
│ │ │                                                         │ │   │
│ │ │                content (text, images)                   │ │   │
│ │ │                                                         │ │   │
│ │ └─────────────────────────────────────────────────────────┘ │   │
│ └─────────────────────────────────────────────────────────────┘   │
└───────────────────────────────────────────────────────────────────┘

Try it · HTML & CSS

Preview (index.html, updates as you type)
  • Padding is space inside the border; the background shows through it.
  • Margin is space outside the border, between this box and its neighbors.
  • Shorthand goes clockwise from the top: margin: top right bottom left. Two values mean vertical, then horizontal.
  • By default, width sets only the content, so padding and border make the box bigger than you asked. box-sizing: border-box makes width include them, which is far easier. Most projects set it on everything with * { box-sizing: border-box; }.

Block and inline elements. Block elements (<div>, <p>, <h1>, <section>) start on a new line and fill the available width. Inline elements (<a>, <strong>, <span>) sit inside a line of text and ignore width and height. display: inline-block gives an inline element a width and height.

Quick check

With box-sizing: content-box (the default), a box has width: 200px; padding: 10px; border: 5px solid;. How wide does it appear on screen?

Layout with Flexbox

Flexbox arranges children in a row or a column, and handles spacing and alignment. It's the tool for navigation bars, toolbars, and rows of cards.

Try it · HTML & CSS

Preview (index.html, updates as you type)
Property (on the container)Does
display: flexlays the children out in a row
flex-direction: columnstacks them instead
justify-contentspacing along the main axis: flex-start, center, space-between, …
align-itemsalignment across it: stretch, center, flex-start, …
gapspace between the children
flex-wrap: wraplets children move to the next line when there's no room

On a child, flex: 1 1 140px means "start at 140px, grow to fill space, and shrink if needed". Make the preview narrower in your mind: when the row gets too tight, the cards wrap.

Layout with Grid

Grid places items in rows and columns at the same time. It's best for page layouts and galleries.

Try it · HTML & CSS

Preview (index.html, updates as you type)
  • grid-template-columns: 180px 1fr makes two columns: 180px, then 1fr, one fraction of the remaining space.
  • repeat(3, 1fr) is three equal columns.
  • grid-column: 1 / 3 makes an item span from column line 1 to line 3, so across both columns.

Flexbox or Grid? Use Flexbox for one direction (a row of buttons, a navbar). Use Grid for two directions (a page layout, a card gallery). They're often combined: a Grid page whose header is a Flexbox row.

Responsive design

A responsive page adapts to the screen: one column on a phone, several on a laptop. Three ingredients:

  1. The viewport meta tag from lesson 2, in every page's <head>.
  2. Flexible sizes: %, fr, max-width, and images with max-width: 100% so they never overflow.
  3. Media queries, which apply CSS only when a condition is true, such as a minimum screen width.

Try it · HTML & CSS

Preview (index.html, updates as you type)

This is mobile-first CSS: the base rules are for phones, and media queries with min-width add columns as the screen grows. Common breakpoints are about 640px (large phones), 768px (tablets), and 1024px (laptops), but choose them where your layout starts to look wrong.

Try it

Exercise · HTML & CSS

Style a profile card

Style the .card: give it padding, a border, a border-radius, and a background. Then make .card .actions a Flexbox row (display: flex) with a gap between the buttons.

Preview (index.html, updates as you type)
Hint

Inside .card write padding: 16px; border: 1px solid #ccc; border-radius: 10px; background: #f6f4ff;. Inside .card .actions write display: flex; gap: 8px;.

Show a solution

Try it yourself first — you learn more from a wrong attempt than from reading an answer.

<style>
  .card {
    max-width: 320px;
    padding: 16px;
    border: 1px solid #d9d4f0;
    border-radius: 10px;
    background: #f6f4ff;
  }
  .card .actions {
    display: flex;
    gap: 8px;
  }
</style>

<div class="card">
  <h2>Ana Reyes</h2>
  <p>3rd year BSCS. Loves web design.</p>
  <div class="actions">
    <button>Message</button>
    <button>Follow</button>
  </div>
</div>

Exercise · HTML & CSS

Responsive gallery

Make .gallery a grid with one column by default (grid-template-columns: 1fr), and three columns when the screen is at least 600px wide, using a @media (min-width: 600px) query.

Preview (index.html, updates as you type)
Hint

Add grid-template-columns: 1fr; to .gallery. Then write @media (min-width: 600px) { .gallery { grid-template-columns: repeat(3, 1fr); } }.

Show a solution

Try it yourself first — you learn more from a wrong attempt than from reading an answer.

<style>
  .gallery {
    display: grid;
    gap: 8px;
    grid-template-columns: 1fr;
  }
  .gallery div { background: #ddd; height: 60px; }

  @media (min-width: 600px) {
    .gallery { grid-template-columns: repeat(3, 1fr); }
  }
</style>

<div class="gallery">
  <div></div><div></div><div></div><div></div><div></div><div></div>
</div>

Common mistakes

  • A missing semicolon or brace, which silently breaks the rules after it. Check the DevTools Styles panel: invalid declarations are crossed out.
  • . vs # mix-ups: .menu is a class, #menu is an ID.
  • Fighting specificity with !important everywhere. Use a class with a clearer selector instead.
  • Forgetting box-sizing: border-box, then wondering why boxes are too wide.
  • Fixed widths in px for whole layouts, which overflow on phones. Use %, fr, and max-width.
  • Forgetting the viewport meta tag, so phones show a tiny zoomed-out page.

Summary

  • A CSS rule is a selector plus property: value; declarations. Prefer external stylesheets.
  • Select by tag, .class, #id, relationships (nav a), and states (:hover). Specificity, then order, decides conflicts.
  • Style text with font-family, font-size, color, line-height; use rem for sizes.
  • Every element is a box: content, padding, border, margin. Use box-sizing: border-box.
  • Flexbox lays things out in one direction; Grid in rows and columns. Media queries make layouts responsive, mobile first.

Next lesson: PHP fundamentals: making pages dynamic on the server.

References and further reading