Skip to main content

HTML and CSS Basics

Learning Objectives

By the end of this page you should be able to:

  • Explain the roles HTML and CSS each play in building a web page and how they interact.
  • Write a valid HTML document using semantic elements instead of generic <div> soup.
  • Build a simple HTML form with the correct input types and labels.
  • Select elements in CSS using element, class, ID, descendant, and pseudo-class selectors, and predict which rule wins when several apply.
  • Describe the CSS box model and calculate an element's rendered width and height from its content, padding, border, and margin.
  • Lay out a page using Flexbox and CSS Grid, and choose the right one for a given layout problem.
  • Write a responsive layout using media queries and relative units.

Quick Answer

HTML (HyperText Markup Language) defines the structure and meaning of a web page — headings, paragraphs, links, images, forms. CSS (Cascading Style Sheets) defines its presentation — colors, spacing, fonts, and layout. They are separate languages by design: HTML says "this is a heading," CSS says "and it should be large, blue, and centered." This separation matters because it lets you redesign a site's entire look by editing one CSS file, keeps content accessible to screen readers and search engines regardless of styling, and lets multiple pages share one stylesheet instead of repeating style code everywhere. Every website you've ever visited is built on this pair, often alongside JavaScript for interactivity.

Introduction

Think of HTML as the skeleton of a webpage and CSS as its skin, clothes, and posture. Neither is optional if you want a real website: HTML with no CSS is legible but ugly (like a Wikipedia page from 1998); CSS with no HTML has nothing to style. Browsers parse HTML into a tree of objects — the DOM (Document Object Model) — and then apply CSS rules to that tree before painting pixels to the screen. Understanding both languages, and how they connect through the DOM, is the foundation for everything else in web development, including JavaScript, frameworks like React, and responsive design.

HTML: Structure and Meaning

Basic HTML Structure

Every HTML document follows the same skeleton: a doctype declaration, an <html> root, a <head> for metadata the browser needs but doesn't display, and a <body> for the visible content.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Basic HTML Page</title>
</head>
<body>
<h1>Welcome to Web Development!</h1>
<p>This is a basic example of an HTML document.</p>
</body>
</html>

A few details worth internalizing:

  • <!DOCTYPE html> tells the browser to render in standards mode rather than a legacy "quirks mode" that mimics old, buggy browser behavior.
  • <meta name="viewport"> is what makes a page usable on phones — without it, mobile browsers render the page at desktop width and shrink it.
  • The <title> text is what shows up in the browser tab and in search engine results — it's not decorative, it's content.

Why Semantic HTML Matters

Early web pages (and many beginner tutorials) wrap everything in <div> tags. It works, but it throws away information. Semantic elements tell the browser, screen readers, and search engines what a section means, not just how to box it.

<body>
<header>
<nav>
<a href="/">Home</a>
<a href="/about">About</a>
</nav>
</header>

<main>
<article>
<h1>How the Web Works</h1>
<p>Browsers request HTML, CSS, and JavaScript files from a server...</p>
</article>
<aside>
<p>Related: Introduction to Web Development</p>
</aside>
</main>

<footer>
<p>&copy; 2026 Web Basics Guide</p>
</footer>
</body>

A screen reader user can jump straight to <main> or <nav> because the browser exposes these as landmarks. A <div> gives none of that for free — you'd have to bolt on ARIA attributes by hand to get back what semantic tags provide automatically.

Key HTML Tags

TagPurpose
<h1><h6>Headings, in order of importance. There should be exactly one <h1> per page.
<p>A paragraph of text.
<a href="...">A hyperlink.
<img src="..." alt="...">An embedded image. alt is required for accessibility.
<ul> / <ol> / <li>Unordered and ordered lists.
<div> / <span>Generic block/inline containers, used when no semantic tag fits.
<header>, <nav>, <main>, <article>, <section>, <aside>, <footer>Semantic layout landmarks.
<table>, <tr>, <td>, <th>Tabular data — not for layout.

Building a Form

Forms are how a page collects user input, and they're one of the most misused parts of HTML by beginners — mainly because the <label> tag gets skipped.

<form action="/submit" method="post">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required>

<label for="email">Email:</label>
<input type="email" id="email" name="email" required>

<label for="plan">Choose a plan:</label>
<select id="plan" name="plan">
<option value="free">Free</option>
<option value="pro">Pro</option>
</select>

<button type="submit">Sign Up</button>
</form>

type="email" gives you free client-side validation and triggers the right on-screen keyboard on mobile. The for/id pairing between <label> and <input> means clicking the label text focuses the input — and it's what lets a screen reader announce "Email, edit text" instead of just "edit text."

CSS: Presentation and Layout

Basic CSS Syntax

A CSS rule is a selector plus a block of declarations, each a property: value; pair.

/* This is a comment in CSS */
h1 {
color: blue; /* text color */
font-size: 24px; /* text size */
}

p {
color: gray;
line-height: 1.5; /* spacing between lines */
}

You attach CSS to HTML in three ways: an external .css file linked via <link rel="stylesheet" href="styles.css"> (preferred — cacheable and reusable), a <style> block in <head>, or an inline style="..." attribute (avoid — hard to maintain and wins almost every specificity fight, for the wrong reasons).

CSS Selectors and the Cascade

Selector typeSyntaxTargets
ElementpEvery <p> on the page
Class.containerEvery element with class="container"
ID#headerThe one element with id="header"
Descendantnav aAny <a> inside a <nav>
Pseudo-classa:hoverAn <a> while the mouse hovers it

When multiple rules target the same element, CSS resolves the conflict using specificity, not the order you'd guess from reading top to bottom.

So #header beats .header, which beats header, regardless of the order they're written — but two rules with equal specificity are decided by source order, which is why "just add another class" sometimes doesn't work the way beginners expect.

The Box Model

Every HTML element is rendered as a rectangular box made of four layers, from the inside out: content, padding, border, and margin.

.box {
width: 200px;
padding: 20px;
border: 5px solid black;
margin: 10px;
}

By default (box-sizing: content-box), that .box actually occupies 200 + 20*2 + 5*2 = 250px of horizontal space — padding and border are added on top of the declared width. Most developers reset this globally:

* {
box-sizing: border-box;
}

With border-box, the declared width includes padding and border, so width: 200px really does render as 200px wide. This single line eliminates a huge class of "why is my layout overflowing" bugs.

Flexbox: One-Dimensional Layout

Flexbox arranges items along a single axis (row or column) and is built for distributing space among items, aligning them, and handling variable-sized content — think navbars, button groups, and centering.

.nav {
display: flex;
justify-content: space-between;
align-items: center;
}
<nav class="nav">
<a href="/">Logo</a>
<a href="/about">About</a>
<a href="/contact">Contact</a>
</nav>

justify-content controls spacing along the main axis; align-items controls alignment along the cross axis. Centering something with Flexbox (display: flex; justify-content: center; align-items: center;) replaced years of hacky position: absolute + negative margin tricks.

CSS Grid: Two-Dimensional Layout

Grid arranges items along rows and columns simultaneously, which makes it the right tool for whole-page layouts.

.page {
display: grid;
grid-template-columns: 200px 1fr;
grid-template-rows: auto 1fr auto;
gap: 16px;
}
<div class="page">
<header style="grid-column: 1 / 3;">Header</header>
<aside>Sidebar</aside>
<main>Main content</main>
<footer style="grid-column: 1 / 3;">Footer</footer>
</div>

A useful rule of thumb: reach for Flexbox when you're arranging items in a line, and Grid when you're arranging items on a plane (a whole page skeleton, a photo gallery, a dashboard). Many real layouts use both — Grid for the page skeleton, Flexbox inside individual components.

Responsive Design

A responsive page adapts its layout to the screen size instead of forcing horizontal scrolling on mobile. The two core tools are relative units and media queries.

.container {
width: 90%;
max-width: 1200px;
margin: 0 auto;
}

@media (max-width: 600px) {
.nav {
flex-direction: column;
}
}

max-width caps the container on large screens while width: 90% keeps it fluid on small ones. The media query overrides the flex direction only when the viewport shrinks below 600px — this is called a breakpoint. Combined with the viewport <meta> tag from earlier, this is the backbone of "mobile-first" design.

Putting It Together

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Styled HTML Page</title>
<style>
* { box-sizing: border-box; }
body {
font-family: Arial, sans-serif;
background-color: #f0f0f0;
margin: 0;
}
h1 { color: darkblue; }
p { color: #333; }
</style>
</head>
<body>
<h1>Welcome to Web Development!</h1>
<p>This is a styled HTML document with CSS.</p>
</body>
</html>

HTML provides the structure and meaning; CSS provides the visual language on top of it. Once this pairing feels natural, the next steps are adding interactivity with JavaScript and learning how the DOM lets scripts change HTML and CSS live in the browser.

Key Terms

TermDefinitionContext/Related Concepts
DOM (Document Object Model)The browser's in-memory tree representation of an HTML document.Manipulated by JavaScript; CSS is applied to it before rendering.
Semantic elementAn HTML tag that describes the meaning of its content, not just its appearance.<header>, <nav>, <article> vs. generic <div>.
SelectorA CSS pattern that determines which elements a rule applies to.Element, class, ID, descendant, pseudo-class selectors.
SpecificityThe algorithm CSS uses to decide which rule wins when several match the same element.Inline styles > ID > class/pseudo-class > element.
Box modelThe layered structure (content, padding, border, margin) that defines every element's rendered size.box-sizing: border-box changes how width is calculated.
FlexboxA one-dimensional CSS layout system for arranging items in a row or column.display: flex, justify-content, align-items.
CSS GridA two-dimensional CSS layout system for arranging items in rows and columns together.display: grid, grid-template-columns.
Media queryA CSS rule that applies styles conditionally based on viewport size or device features.Core mechanism behind responsive design and breakpoints.
CascadeThe process by which CSS combines specificity, source order, and importance to resolve conflicting rules.!important overrides normal specificity ordering.
ViewportThe visible area of a web page on a device's screen.Controlled via <meta name="viewport">.

Common Mistakes

Misconception 1: "Divs and spans are enough — semantic tags are just extra typing." Why it's wrong: <div> and <span> carry no meaning, so screen readers, search engine crawlers, and browser accessibility tools can't tell a navigation bar from a footer from a sidebar. Correct explanation: Use semantic tags (<nav>, <main>, <article>, <footer>, etc.) wherever one fits the content's role, and reserve <div>/<span> for cases with no semantic equivalent, like a purely visual wrapper for styling hooks.

Misconception 2: "Setting width: 200px guarantees the element is 200px wide on screen." Why it's wrong: by default, CSS uses box-sizing: content-box, which adds padding and border outside the declared width, so a 200px box with 20px padding and a 5px border actually renders at 250px wide. Correct explanation: set box-sizing: border-box (commonly applied globally with a * selector) so that width and height include padding and border, making sizing predictable.

Misconception 3: "CSS rules apply in the order they're written, top to bottom, full stop." Why it's wrong: source order is only the tiebreaker of last resort. CSS first resolves conflicts by specificity — an ID selector beats a class selector beats an element selector, no matter which one appears later in the file. Correct explanation: figure out which rule wins by comparing specificity first (inline style > ID > class/attribute/pseudo-class > element), and only fall back to "last one written wins" when specificity is tied.

Comparison and Connections

Concept AConcept BKey Difference
Class selector (.name)ID selector (#name)A class can be reused on many elements and has lower specificity; an ID must be unique per page and has higher specificity.
Block element (e.g. <div>, <p>)Inline element (e.g. <span>, <a>)Block elements start on a new line and take full available width; inline elements flow within a line and only take the width of their content.
FlexboxCSS GridFlexbox is one-dimensional (a row or a column); Grid is two-dimensional (rows and columns at once), better suited for whole-page layout.
MarginPaddingMargin is space outside an element's border (between elements); padding is space inside the border (between the border and the content).
position: relativeposition: absoluterelative positions an element relative to its own normal position and still occupies space in the layout; absolute removes it from normal flow and positions it relative to the nearest positioned ancestor.
External stylesheetInline style attributeExternal stylesheets are cacheable, reusable across pages, and easy to maintain; inline styles apply to one element only and have very high specificity, making overrides harder.

Practice Questions

Recall

  1. What are the four layers of the CSS box model, from innermost to outermost? Answer guidance: Content, padding, border, margin — content is the actual text/image, padding is space inside the border, the border is the visible edge, and margin is space outside the border separating it from other elements.

  2. Name three semantic HTML elements and what each represents. Answer guidance: Any three of: <header> (introductory content/branding), <nav> (navigation links), <main> (the page's primary content), <article> (self-contained content), <aside> (tangential content like a sidebar), <footer> (closing content like copyright).

Understanding

  1. Explain why box-sizing: border-box is commonly applied to every element in a stylesheet. Answer guidance: By default, padding and border add to an element's declared width/height (content-box), making sizes unpredictable when padding changes. border-box makes the declared width/height include padding and border, so the element's rendered size stays exactly what you set regardless of padding — this avoids unexpected overflow and simplifies layout math.

  2. Why does CSS specificity matter more than the order rules are written in? Answer guidance: Because CSS resolves conflicting declarations by comparing specificity (inline > ID > class/pseudo-class > element) before ever looking at source order. Source order is only the tiebreaker when two rules have identical specificity. Without understanding this, developers get confused when a later rule doesn't override an earlier, more specific one.

Application

  1. You need a navbar with a logo on the left and three links evenly spaced on the right, all vertically centered. Which CSS layout tool would you use, and how? Answer guidance: Flexbox. Set the nav container to display: flex; justify-content: space-between; align-items: center;, put the logo as the first child and the links (possibly wrapped in another flex container) as the second child.

  2. You're building a photo gallery that should show 4 columns on desktop and 1 column on mobile. Sketch the CSS approach. Answer guidance: Use CSS Grid with display: grid; grid-template-columns: repeat(4, 1fr); gap: 16px; for the default (desktop) layout, then wrap a @media (max-width: 600px) { .gallery { grid-template-columns: 1fr; } } media query to collapse to a single column on small screens.

Analysis

  1. A developer writes #nav a { color: red; } and later .link { color: blue; }, then applies both selectors to the same <a> element. What color renders, and why? Answer guidance: Red. #nav a has an ID plus an element (specificity roughly 1-0-1) which outranks .link's single class (specificity 0-1-0), regardless of which rule was written second.

  2. Compare using <div> elements styled to look like buttons versus using <button> elements for a "Submit" action. What breaks with the <div> approach? Answer guidance: A styled <div> gets no keyboard focus, no Enter/Space activation, no accessible role announcement by screen readers, and doesn't participate in native form submission — all of which <button> provides for free. The <div> approach requires manually re-implementing accessibility and form behavior with JavaScript and ARIA attributes, which is more code and easier to get wrong.

FAQ

Do I need to learn HTML and CSS before JavaScript? Yes, in practice. JavaScript in the browser mostly exists to manipulate the DOM (built from HTML) and to change styles (defined in CSS), so you need a working mental model of both before DOM manipulation makes sense.

What's the difference between CSS and Sass/LESS? Sass and LESS are "CSS preprocessors" — languages that compile down to plain CSS but add features like variables, nesting, and mixins. Modern CSS has adopted native variables (--custom-property) and nesting, closing much of the gap, but preprocessors are still common in larger codebases.

Why does my CSS not apply to an element? The most common causes: a more specific rule elsewhere overrides it, a typo in the selector or property name, the stylesheet isn't linked correctly, or the CSS loaded before the HTML it targets (rare, since stylesheets don't depend on load order the way scripts can).

Is inline CSS (the style attribute) ever a good idea? Occasionally — for dynamically computed values set by JavaScript (like a progress bar's width) where writing to a class doesn't make sense. As a rule for hand-written styling, avoid it: it's hard to maintain, can't be reused, and has very high specificity that makes later overrides painful.

What is "mobile-first" design? It's writing your base CSS for small screens first, then using min-width media queries to add complexity for larger screens, rather than the reverse. It tends to produce simpler, more performant CSS because you're progressively enhancing rather than trying to undo desktop styles for mobile.

Do I need to memorize every CSS property? No. Focus on understanding the box model, selectors/specificity, and the two layout systems (Flexbox and Grid) deeply — those explain most of what you'll encounter. Specific property names are easy to look up once the underlying model makes sense.

What happens if I forget the alt attribute on an <img>? The image becomes invisible to screen reader users (who hear nothing useful, or the raw filename), and if the image fails to load, sighted users see nothing informative either. Search engines also use alt text to understand image content.

Quick Revision

  • HTML defines structure/meaning; CSS defines presentation; the browser combines them via the DOM before rendering.
  • Every HTML document needs <!DOCTYPE html>, <html>, <head>, and <body>.
  • Prefer semantic tags (<nav>, <main>, <article>, <footer>) over generic <div> where one fits.
  • Forms need <label for="id"> paired with a matching <input id="id"> for accessibility.
  • A CSS rule = selector + declarations (property: value;).
  • Specificity order: inline style > ID > class/attribute/pseudo-class > element; source order only breaks ties.
  • The box model, inside-out: content → padding → border → margin.
  • box-sizing: border-box makes declared width/height include padding and border — set it globally to avoid layout surprises.
  • Flexbox = one-dimensional layout (a row or column); CSS Grid = two-dimensional layout (rows and columns together).
  • Media queries (@media (max-width: ...)) apply CSS conditionally based on viewport size, enabling responsive design.
  • Margin is outside the border (space between elements); padding is inside the border (space around content).
  • Use external stylesheets over inline styles for maintainability and specificity control.

Prerequisites

Related Topics

Next Topics