Learn to Code HTML & CSS – Free Online Book – Shay Howe BSIT BSCS

BSIT and BSCS students who are starting web technologies can use Learn to Code HTML & CSS by Shay Howe, a free set of online lessons for complete beginners. It teaches you to build and style a real website with HTML and CSS, from the structure of a page and the box model to forms, tables, media and clean coding habits, by building one project, a conference website, step by step. A second course, Advanced HTML & CSS, goes on to responsive design, complex selectors, transforms, animations, Sass and jQuery. There is no PDF on the official site, so this page links to the lessons.

Read it knowing which era it comes from. The lessons carry no edition number or date, and the advanced course still talks about Internet Explorer 6 to 9, jQuery 1.9 and Ruby-based tools, while the layout lessons use floats and inline-block columns and mention Flexbox and Grid only as emerging specifications. The beginner course remains a good foundation. The site shows only a copyright notice for Shay Howe and states no open licence, so this page contains only original study notes: our own lesson summaries, key points and practice questions, with nothing copied from the lessons.

Book Overview

CourseWeb Technologies / Front-End Web Development
Degree ProgramsBSIT, BSCS
LevelUniversity / Undergraduate (beginner, with an advanced course)
EditionOnline lessons; no edition number or revision date is shown on the site
AuthorShay Howe
Print EditionNew Riders, ISBN 978-0-321-94052-0 (sold separately)
Structure22 lessons in 2 courses: Course 101 HTML & CSS (12 lessons) and Course 201 Advanced HTML & CSS (10 lessons)
PrerequisitesNone for Course 101; basic computer use and a plain text editor
PracticeCourse 101 builds one running project (the Styles Conference website) step by step; no graded end-of-lesson exercises
LanguageEnglish
Copyright© Shay Howe; no open licence is stated on the site
FormatFree online lessons (HTML); no PDF on the official site

Chapter List

Course 101, Lesson 1: Building Your First Web Page

Course 101: HTML & CSS · Difficulty: Easy · Key topics: HTML vs CSS, elements, tags, attributes, document structure, selectors, external stylesheet, CSS reset

The first lesson splits web design into two jobs. HTML gives content its structure and meaning, CSS controls how it looks, and the two should live in separate files. You learn the vocabulary of HTML (elements, tags and attributes), then build the required page skeleton in a plain text editor: the doctype, html, head and body. On the CSS side it defines selectors, properties and values, compares type, class and ID selectors, links one external stylesheet, and adds a CSS reset so browsers start from the same baseline. It also starts the Styles Conference site that the rest of Course 101 keeps building.

Key Points:

  • An element is an opening tag, content and a closing tag; attributes such as id, class, src and href sit in the opening tag as name and value pairs.
  • Every page needs <!DOCTYPE html>, then html with a head (title, metadata, linked files) and a body (everything visible).
  • Void elements such as meta, img, br, hr, input and link have no closing tag.
  • A CSS rule is a selector plus declarations; each declaration is a property, a colon, a value and a semicolon.
  • A class selector (.name) can be reused many times; an ID selector (#name) must appear once per page.
  • Keep styles in one external file linked from the head, not inline, and put a reset at the top of it because CSS is read from top to bottom.

Practice Tip: Make a folder with index.html and main.css, link the stylesheet in the head, then add h1 { color: red; } and refresh the browser. If the heading does not change, your link path is wrong, which is the most common first bug.

Common Mistake: Writing the page in a word processor or saving it with a .txt ending. Use a plain text editor and save the file with the .html extension.

Important Questions:

  • What is the difference between HTML and CSS? HTML supplies the structure and meaning of the content (headings, paragraphs, images); CSS controls its presentation (fonts, colours, layout). They should be kept in separate files.
  • Why link an external stylesheet instead of using inline or internal styles? One shared file is easier to maintain and reuse across pages, and the browser can cache it.

Course 101, Lesson 2: Getting to Know HTML

Course 101: HTML & CSS · Difficulty: Easy · Key topics: semantics, div and span, block vs inline, headings, strong and em, structural elements, special characters, hyperlinks

Lesson 2 is about choosing the right element, not the one that looks right. It explains semantics and why browsers, screen readers and search engines depend on it, then separates block-level and inline-level elements and introduces div and span as meaning-free containers. After headings, paragraphs, strong and em, it covers the HTML5 structural elements (header, nav, article, section, aside, footer) and when to use each. The second half is hyperlinks: relative and absolute paths, email links, new windows and links within a page. You then add structure, navigation and four more pages to the conference site.

Key Points:

  • Semantics means picking the element that describes what the content is; it helps assistive technology, search engines and future maintainers.
  • Block-level elements start on a new line and take the full width; inline-level elements flow with the text and take only their own width.
  • h1 to h6 express hierarchy, not size; strong and em carry importance and stress, while b and i are only stylistic.
  • Use article for self-contained content, section for a themed group, and div only when you need a styling hook.
  • A relative path links inside your own site; an absolute path carries the full URL, including http.
  • target="_blank" opens a link in a new window, and #id links to an element on the same page.
  • Special characters are written as entities that start with & and end with ;.

Practice Tip: Build a four-page mini site with the same navigation list on every page, then click every link from every page. Any relative path that breaks on one page shows you how folders and paths really work.

Common Mistake: Choosing a heading level because of its default size, or mixing up header (the introduction to a page or section) with head (the hidden metadata of the document).

Important Questions:

  • When should you use article, section or div? Use article for content that makes sense on its own, section for a thematic group that usually has a heading, and div when you only need a container for styling.
  • What is the difference between a relative and an absolute path? A relative path points to a file from the current location within the site; an absolute path gives the full address, so it is used for other websites.

Course 101, Lesson 3: Getting to Know CSS

Course 101: HTML & CSS · Difficulty: Medium · Key topics: cascade, specificity, combining selectors, multiple classes, colour formats, length units

This lesson explains why one rule beats another. Styles are applied from top to bottom, so a later rule overrides an earlier one, but only when the selectors are equally specific. You learn to score selectors by type, class and ID, to combine selectors (descendant and chained) and to read them from right to left. It then shows how stacking several classes on one element keeps code modular, and closes with the values you type most: four colour formats (keywords, hex, RGB and RGBa, HSL and HSLa) and three lengths (pixels, percentages and em). The Styles Conference site itself does not change in this lesson.

Key Points:

  • Specificity is counted in three columns, IDs then classes then types: type is 0-0-1, class is 0-1-0, ID is 1-0-0. It is not a base-10 number.
  • The rightmost part of a selector is the key selector; everything to its left is a prequalifier.
  • A space means a descendant (.box p); no space means the same element (.box.big).
  • An element can carry several space-separated classes, so shared styles go in one class and variations in another.
  • Hex can be shortened when pairs repeat (#ff6600 becomes #f60); rgba() and hsla() add an opacity value from 0 to 1.
  • A percentage length is relative to the parent element; em is relative to the element’s font size.

Practice Tip: Give one paragraph an ID and a class, write conflicting colours for the type, the class and the ID, and predict the winner before you refresh. Then swap the rule order to prove that specificity beats position.

Common Mistake: Reading specificity as one ordinary number, so that eleven classes seem to beat one ID. Compare the columns from the left instead.

Important Questions:

  • How is selector specificity calculated? Count IDs, classes and element types in three columns. The selector with the higher value in the leftmost differing column wins; if tied, the later rule wins.
  • Which colour format should you use when you need transparency? Use rgba() or hsla(), which take an alpha value from 0 to 1; hex is fine for solid colours.

Course 101, Lesson 4: Opening the Box Model

Course 101: HTML & CSS · Difficulty: Medium · Key topics: display, box model, width and height, margin and padding, borders, border-radius, box-sizing, developer tools

Lesson 4 treats every element as a rectangle. It starts with the display property (block, inline, inline-block and none), then breaks the box into content, padding, border and margin, with the formula for an element’s total width and height. You practise the shorthand rules for one, two and four values, border styles and rounded corners, and the three values of box-sizing, ending with a recommendation to use border-box. A short section teaches the browser developer tools for inspecting a box. The practice section sets universal border-box, a centred 960px container, button classes and a hero section.

Key Points:

  • Total width is margin + border + padding + width + padding + border + margin; a 400px box with 20px padding, 6px borders and 20px margins renders 492px wide.
  • Inline elements ignore width and height; block and inline-block elements accept them.
  • Margin is outside the border and transparent; padding is inside it and shows the element’s own background.
  • Shorthand values: one value for all sides, two for vertical then horizontal, four clockwise from the top.
  • The border shorthand order is width, style, colour; border-radius rounds the corners.
  • box-sizing: border-box counts padding and border inside the width and height; padding-box is deprecated.
  • margin: 0 auto centres a block with a set width.

Practice Tip: Create a 400px by 100px div with 20px padding, a 6px border and 20px margin, open the browser inspector and check the Computed box diagram. It should show 492px by 192px.

Common Mistake: Setting width: 100% and then adding padding or a border, which makes the box overflow its parent under the default sizing. Switch to border-box.

Important Questions:

  • How is the total width of an element calculated in the default box model? Add the content width, the left and right padding, the left and right borders and the left and right margins.
  • Why does the lesson recommend box-sizing: border-box? Width and height then include padding and border, so sizes stay predictable and units can be mixed, for example a 40% width with pixel padding.

Course 101, Lesson 5: Positioning Content

Course 101: HTML & CSS · Difficulty: Medium · Partly dated: layout techniques predate Flexbox and Grid · Key topics: float, clear, clearfix, inline-block grids, white space, position relative and absolute

This lesson shows three ways to place content. Floats push an element left or right so text wraps around it, which also lets block elements sit side by side; you then learn the side effects, and the clear property and the clearfix pattern that contain them. Inline-block gives columns without clearing but leaves gaps between them, which you remove with tag placement or empty comments. It then builds a reusable 960px grid of one-third and two-thirds columns for the conference site, and finishes with the position property for one-off placement. The author only mentions Flexbox and Grid as emerging specifications.

Key Points:

  • A floated element leaves normal flow, shrinks to its content width and lets following content wrap around it.
  • clear: both on a later element, or a clearfix on the parent, stops a layout collapsing around floats.
  • A clearfix uses :before and :after with display: table, empty content and clear: both.
  • Inline-block columns show a small gap from the white space between tags, so adjacent columns can wrap onto a new line.
  • The author prefers inline-block for page grids and floats for wrapping text around images.
  • position: relative offsets an element from its own spot; absolute places it against the nearest positioned ancestor.

Practice Tip: Make three columns with float: left, put them in a parent with a background colour, and watch the background vanish. Then add the clearfix and see it return.

Common Mistake: Giving a positioned child position: absolute without making the parent position: relative, so it jumps to the corner of the whole page.

Important Questions:

  • Why does a parent with only floated children collapse, and how do you fix it? Floats leave normal flow, so the parent gets no height. Contain them with a clearfix or add a cleared element after them.
  • How do relative and absolute positioning differ? Relative keeps the element’s original space and shifts it from there; absolute removes it from the flow and positions it against the nearest positioned ancestor.

Course 101, Lesson 6: Working with Typography

Course 101: HTML & CSS · Difficulty: Medium · Key topics: typeface vs font, colour, font properties, line height, text properties, web-safe fonts, @font-face, Google Fonts, cite and quotes

Lesson 6 starts with the difference between a typeface and a font, then gives text a colour and works through the font properties: family stacks with fallbacks, size, style, variant, weight (numeric 100 to 900), line height and the font shorthand. A second group of text properties covers alignment, decoration, indent, shadows, transforms and letter and word spacing. After that you choose between web-safe fonts and embedded web fonts with @font-face, with a warning about font licences, and practise adding a Google Font. It ends with the semantic elements for citations and quotations: cite, q and blockquote.

Key Points:

  • A typeface is the design; a font is the file that delivers it.
  • A font-family list is a fallback stack and should end with a generic family such as serif or sans-serif.
  • font-weight uses numbers from 100 to 900, where 400 is normal and 700 is bold.
  • A line height of about 1.5 keeps body text readable.
  • The font shorthand requires at least a size and a family, and size and line height are separated by a slash.
  • Embedding a font does not grant permission to use it, so check the font’s licence.
  • blockquote is for long quotations, q for short inline ones and cite for the title of a work.

Practice Tip: Write the same paragraph with four different font-family stacks, one of which starts with a font you do not have installed. The browser falls back down the list, which makes the idea of a stack easy to see.

Common Mistake: Leaving out the font size or the family in the font shorthand. Without both, the whole declaration is invalid and the browser ignores it.

Important Questions:

  • What is the difference between a typeface and a font? A typeface is the visual design of the letters; a font is the file or format that delivers that design to the screen.
  • Why does a font-family declaration list several fonts? If the first font is unavailable the browser tries the next, and the final generic keyword guarantees a sensible fallback.

Course 101, Lesson 7: Setting Backgrounds & Gradients

Course 101: HTML & CSS · Difficulty: Medium · Key topics: background-color, background-image, repeat, position, shorthand, linear and radial gradients, colour stops, multiple backgrounds, size, clip, origin

Backgrounds are treated here as a design tool for grouping content and signalling priority. The lesson adds a colour (with a hex fallback before an rgba() value for old Internet Explorer), then an image with url(), followed by background-repeat, background-position and the shorthand. Gradients come next: linear gradients with keyword or degree directions, radial gradients and optional colour stops, always with a solid fallback. It then layers several images on one element and explains background-size (including cover and contain), background-clip and background-origin, using the conference site’s rows and lead sections as practice.

Key Points:

  • background accepts colours and images; background-color accepts only solid colours.
  • By default an image tiles from the top-left corner; repeat-x, repeat-y and no-repeat change that.
  • background-position takes a horizontal and a vertical offset as keywords, lengths or percentages.
  • A gradient is a background image: linear-gradient() runs in a direction, radial-gradient() spreads from a centre, and a colour stop sets where a colour sits.
  • With multiple backgrounds the first image listed is on top and the last is at the back.
  • cover fills the element and may crop; contain shows the whole image and may leave gaps.

Practice Tip: Take one photo and try cover, contain and auto 75% sizes on the same 200px by 240px box with a dashed border. The difference is obvious after one refresh each.

Common Mistake: Declaring a gradient with no solid colour before it. Browsers that do not understand the gradient then show no background at all.

Important Questions:

  • What is the difference between background-size cover and contain? cover scales the image to fill the element and may crop it; contain scales it to fit entirely and may leave empty space.
  • How do you give a transparent background a safe fallback? Declare a hex colour first and the rgba() colour below it; browsers that understand alpha use the second.

Course 101, Lesson 8: Creating Lists

Course 101: HTML & CSS · Difficulty: Easy · Key topics: ul, ol, dl, start and reversed, nesting, list-style, horizontal lists, navigation menus

Lesson 8 covers the three kinds of HTML list: unordered (ul), ordered (ol) and description (dl with dt and dd). Ordered lists get the start, reversed and value attributes, and the lesson explains how to nest one list inside an li of another. On the CSS side it covers list-style-type, custom image markers, list-style-position and the shorthand, then two ways of turning a list into a horizontal menu: inline-block or float. The practice section converts the conference site’s links into real navigation lists and builds the speakers page.

Key Points:

  • Use ul when order does not matter, ol when it does, and dl for term and description pairs.
  • The only direct children of a ul or ol are li elements; nested lists go inside an li.
  • start sets the first number, reversed counts down, and value on an li renumbers from that item.
  • list-style-type accepts values such as disc, square, decimal, lower-roman and none, on either list type.
  • list-style-position: inside wraps text beneath the marker instead of beside it.
  • Horizontal menus use display: inline-block on the li items, or floats that must be cleared.

Practice Tip: Turn a five-link list into a horizontal menu with inline-block, then remove the gaps between items using empty HTML comments. You will see the white-space problem from Lesson 5 again.

Common Mistake: Placing a nested ul directly inside another ul instead of inside one of its li items.

Important Questions:

  • When do you use a description list? For glossaries and any set of terms with descriptions: dt holds the term and dd holds its description.
  • How do you display a list horizontally? Set display: inline-block on the list items, or float them left and clear the floats.

Course 101, Lesson 9: Adding Media

Course 101: HTML & CSS · Difficulty: Easy · Key topics: img and alt, image sizing, audio, video, source fallbacks, poster, iframe, figure and figcaption

This lesson covers the media elements of HTML5. For images it explains the required src and alt attributes, the GIF, JPG and PNG formats, sizing with attributes or CSS, and floating or blocking an image, plus when to use img versus a CSS background. Audio and video share the same pattern: controls, autoplay, loop, preload, several nested source elements and a download link as a last fallback. Inline frames embed other pages such as a map, and figure with figcaption marks up self-contained media. The practice work adds teaser photos, round speaker photos and map frames to the site.

Key Points:

  • img is an empty inline element; src is required and alt supplies text for assistive technology and for images that fail to load.
  • JPG suits photographs; PNG suits transparency, icons and flat colour.
  • Setting one dimension keeps the aspect ratio; setting both can distort the image.
  • Use img for meaningful content images and background-image for decoration.
  • audio and video use nested source elements with a type; the browser plays the first format it supports.
  • The poster attribute sets the image shown before a video plays.
  • An iframe loads another page and does not inherit your page’s styles.

Practice Tip: Add a video with controls and a poster image, then deliberately break the src to see your fallback link appear.

Common Mistake: Leaving out alt text, or writing filler such as “image” in it. Describe what the picture shows, or leave it empty only when the image is purely decorative.

Important Questions:

  • Why do audio and video elements contain several source elements? Browsers support different file formats, so you list more than one and the browser uses the first it can play.
  • When should an image be an img element rather than a CSS background? When it is part of the content and carries meaning; decorative or interface images belong in CSS.

Course 101, Lesson 10: Building Forms

Course 101: HTML & CSS · Difficulty: Medium · Key topics: form, input types, textarea, radio and checkbox, select, buttons, label, fieldset and legend, hint text and required

Lesson 10 is about collecting input from users, with back-end processing deliberately left out. It starts with the form element and its action and method, then text inputs and the HTML5 types (email, number, date, range, colour and more), and the textarea. Multiple-choice controls follow: radio buttons, check boxes, and select menus with option. After submit inputs and buttons, hidden and file inputs, it organises forms with label, fieldset and legend and adds disabled, hint text and required. A login form and the conference registration page are built and styled.

Key Points:

  • action is the URL that receives the data and method is how it is sent.
  • Every control needs a name, because the name is what the server receives with the value.
  • Radio buttons in one group share a name; check boxes allow several selections under one name.
  • Connect a label to its control with for and a matching id, so clicking the label focuses the control.
  • fieldset groups related controls and legend captions the group.
  • required blocks submission of an empty field; grey hint text shown inside a field is only a prompt, not pre-filled data.
  • A hidden input is visible in the page source, so never put sensitive data in it.

Practice Tip: Build a registration form with a required name, an email field, a select for number of passes and a textarea. Submit it empty and read the browser’s own validation messages.

Common Mistake: Giving each radio button a different name, which stops them acting as a group so the user can select all of them.

Important Questions:

  • How do you make a label focus its input when clicked? Give the input an id and set the label’s for attribute to the same value, or wrap the input inside the label.
  • What is the difference between hint text and a value? Hint text is a prompt that disappears when the field gets focus; value is real data that is pre-filled and submitted.

Course 101, Lesson 11: Organizing Data with Tables

Course 101: HTML & CSS · Difficulty: Medium · Key topics: table, tr, td, th and scope, caption, thead, tbody, tfoot, colspan and rowspan, border-collapse, striping, alignment

The lesson begins with a reminder that tables are for data, not page layout, which was a common abuse before CSS layout worked. You build a table from table, tr and td, add header cells with th and the scope attribute, then structure it with caption, thead, tbody and tfoot and merge cells with colspan and rowspan. Styling covers border-collapse, border-spacing, row dividers, zebra striping with nth-child and text alignment, ending with a fully styled table. The final practice step builds the conference schedule as three day tables and closes the Styles Conference project.

Key Points:

  • Use tables for tabular data only; layout belongs to CSS.
  • th marks a header cell and scope (col or row) says which cells it describes, which screen readers use.
  • caption must come directly after the opening table tag.
  • thead, tbody and tfoot group rows and cannot be nested inside each other.
  • colspan merges cells across columns and rowspan across rows; the default is 1.
  • border-collapse: collapse merges adjacent borders; border-spacing works only with separate.
  • tbody tr:nth-child(even) creates zebra stripes without extra classes.

Practice Tip: Make a small price table with a header, a body and a footer total, then toggle border-collapse between separate and collapse to see doubled borders appear and disappear.

Common Mistake: Trying to put a border on a tr and wondering why nothing appears. Put the border on the cells instead.

Important Questions:

  • What does the scope attribute do? It states whether a header cell describes a column, a row or a group, so assistive technology can read the data correctly.
  • What is the difference between border-collapse separate and collapse? separate keeps each cell border and the gap between them; collapse merges neighbouring borders into one.

Course 101, Lesson 12: Writing Your Best Code

Course 101: HTML & CSS · Difficulty: Easy · Key topics: valid markup, semantic elements, naming, alt text, separating content from style, divitis, CSS organisation, shorthand, modular styles

The last beginner lesson teaches no new syntax. It collects habits for professional HTML: valid, correctly nested markup, semantic elements, a proper document structure, tidy syntax (lowercase, indented, double quotes), practical class and ID names, useful alt text, no inline styles, no pile of nested div elements, and regular refactoring. The CSS half covers comments, one declaration per line, lowercase hyphenated class names, short selectors, shorthand and three-character hex values, dropping units from zero, grouping vendor prefixes and building reusable modules such as a shared box class. It ends with a list of reference sites and the point that these habits apply to any language.

Key Points:

  • Browsers forgive errors, so validate your markup; an ID may appear only once per page.
  • Name classes and IDs by purpose, not appearance: alert, not red.
  • Never use inline styles; keep content in HTML and presentation in the stylesheet.
  • Avoid “divitis”, the habit of wrapping everything in nested div elements when a semantic element would do.
  • Keep selectors short, avoid IDs in selectors and limit nesting to two or three levels.
  • Use shorthand when setting all sides and longhand when setting one side, so you do not overwrite other values.
  • Write 0 without a unit, and use #ddd rather than #DDDDDD.

Practice Tip: Take your Lesson 11 stylesheet and refactor it: add section comments, shorten every selector chain, and merge duplicated declarations into one shared class. Check that the page looks identical afterwards.

Common Mistake: Naming a class after its look, such as .red-box. When the design changes, the name lies about what the class does.

Important Questions:

  • Why should you keep content and style separate? Markup stays meaningful, styles are reusable and one stylesheet change updates every page, which inline styles make impossible.
  • What is divitis and how do you avoid it? It is overusing nested div wrappers. Use semantic elements such as article and headings, and add a wrapper only when you need one.

Course 201, Lesson 1: Performance & Organization

Course 201: Advanced HTML & CSS · Difficulty: Medium · Partly dated: Apache-only server setup and old-browser notes · Key topics: style architecture, OOCSS, SMACSS, selector performance, minifying, gzip, image sprites, data URIs, caching

The advanced course opens with the idea that a growing site needs a plan. You learn to treat the site as a system of base styles, reusable components and page modules instead of page-by-page CSS, and meet two naming philosophies, Object Oriented CSS and SMACSS. The lesson then ties selectors to speed: keep them short, favour classes and avoid IDs. The rest is the performance checklist of its time: remove duplication, minify files, enable gzip through an Apache .htaccess file, compress images, cut HTTP requests with combined files, sprites and data URIs, and set expiry headers so repeat visitors reuse cached files.

Key Points:

  • Organise styles by intent: base (site-wide defaults), components (buttons, forms, nav) and modules (header, footer, aside).
  • OOCSS separates structure from skin and content from container; SMACSS sorts rules into Base, Layout, Module, State and Theme.
  • Browsers match selectors right to left, so the key selector matters most; long chains like header nav ul li a are slow and fragile.
  • Gzip compresses text files and the lesson measured about a 60% size reduction; lossless image compression removes metadata without losing quality.
  • An image sprite puts many icons in one file and shows each with background-position, saving requests.
  • Suggested cache lifetimes are about one month for images and media and about one year for CSS and JavaScript, with file versioning for files that change.

Practice Tip: Open your browser’s Network panel on any site you made, note the number of requests and the total size, then combine your CSS files into one and compare the numbers.

Common Mistake: Repeating the same declarations in many rules instead of sharing a base class or grouping selectors, which bloats the file and makes changes painful.

Important Questions:

  • Why are ID selectors discouraged in a large stylesheet? They are very specific and cannot be reused, so overriding them forces ever stronger selectors; the lesson compares them to using !important.
  • How do you reduce HTTP requests? Combine CSS into one file and JavaScript into one file, use image sprites for icons, and embed very small images as data URIs.

Course 201, Lesson 2: Detailed Positioning

Course 201: Advanced HTML & CSS · Difficulty: Medium · Partly dated: Internet Explorer 6 and 7 workarounds · Key topics: DOM tree, containing floats, overflow, clearfix, position values, box offsets, fixed, z-index

Lesson 2 goes deeper into the two ideas from the beginner positioning lesson. First it explains the DOM as a tree of parents, children and siblings, then shows why a parent of floated children collapses to zero height and compares three fixes: an empty clearing element, overflow on the parent and the clearfix. Each fix has trade-offs and old Internet Explorer hacks. The second half covers the position property in full (static, relative, absolute and fixed), how top, right, bottom and left behave for each, how to span a full width with fixed headers, and how z-index stacks overlapping positioned elements.

Key Points:

  • A parent that contains only floated children collapses to a height of zero.
  • overflow: auto or hidden on the parent contains floats but can clip shadows and dropdowns that extend outside it.
  • The clearfix (:before and :after pseudo-elements) is more code but avoids clipping; only one of each pseudo-element is allowed per element.
  • A relative element keeps its original space; an absolute element leaves the flow and positions against the nearest positioned ancestor, or the page body if there is none.
  • A fixed element positions against the viewport and stays put while the page scrolls.
  • z-index works only on positioned elements; a higher value stacks on top regardless of source order.

Practice Tip: Create four overlapping absolutely positioned boxes and give them different z-index values. Change one value at a time and predict which box ends up on top.

Common Mistake: Adding z-index to an element whose position is still static. It has no effect until the element is positioned.

Important Questions:

  • What are the three ways to contain floats? Add a clearing element at the end of the parent, set overflow on the parent, or use a clearfix with pseudo-elements.
  • How does a fixed element differ from an absolute one? Both leave the normal flow, but fixed is positioned against the browser viewport and does not move when the page scrolls.

Course 201, Lesson 3: Complex Selectors

Course 201: Advanced HTML & CSS · Difficulty: Medium · Partly dated: Internet Explorer shim advice · Key topics: child and sibling selectors, attribute selectors, pseudo-classes, nth-child, pseudo-elements

Complex Selectors widens your toolkit beyond type, class and ID. It starts with descendant and direct-child selectors, then the general and adjacent sibling combinators, which power a CSS-only toggle menu built from a hidden checkbox. Attribute selectors (present, equals, contains, begins with, ends with and the spaced and hyphenated forms) are used to add file-type icons to links. A long section covers pseudo-classes for links, user actions, form state, structure (:nth-child and its an+b expressions), :target, :empty and :not(), followed by pseudo-elements such as :before, :after and ::selection. It closes with browser-support and speed warnings.

Key Points:

  • article h2 matches any descendant; article > p matches only direct children.
  • h2 + p is the adjacent sibling (the very next one); h2 ~ p is every following sibling with the same parent.
  • a[href$=".pdf"] matches links whose address ends in .pdf; ^= means begins with and *= means contains.
  • :nth-child(2n+1) picks every odd child; odd and even are keywords for the common cases.
  • :first-of-type and its relatives count only siblings of the same element type.
  • :before and :after need the content property; ::selection supports only a few properties, such as colour and background.

Practice Tip: Build a zebra-striped table using only tr:nth-child(even), then round the first and last corners with :first-child and :last-child. No extra classes should be needed.

Common Mistake: Confusing :nth-child with :nth-of-type. The first counts every sibling; the second counts only siblings of the same element type.

Important Questions:

  • What is the difference between h2 + p and h2 ~ p? h2 + p selects only the paragraph immediately after an h2; h2 ~ p selects every paragraph sibling that follows it.
  • What is the difference between a pseudo-class and a pseudo-element? A pseudo-class selects an element in a certain state or position (:hover, :first-child); a pseudo-element selects a part of an element or generated content (::selection, :before).

Course 201, Lesson 4: Responsive Web Design

Course 201: Advanced HTML & CSS · Difficulty: Medium · Partly dated: old-browser polyfills and viewport notes · Key topics: flexible grids, media queries, breakpoints, mobile first, viewport meta tag, flexible media

This is the course’s most useful lesson today. It defines responsive design as one site that adapts to every screen, distinguishes it from adaptive and separate mobile sites, and builds a flexible grid from relative units using the target divided by context formula. Media queries come next, with media types, logical operators and features such as width, orientation and pixel ratio. The lesson advises setting breakpoints where the design breaks, not at device widths, and writing mobile-first styles with min-width queries. It then covers the viewport meta tag and flexible images, video and embedded iframes, using a padding-bottom ratio box.

Key Points:

  • Flexible layouts use percentages or em; the formula is target divided by context, where context is the parent’s width.
  • A media query combines a media type with features, for example @media screen and (min-width: 600px).
  • Choose breakpoints where the layout starts to break, not at fixed device widths, because new devices keep appearing.
  • Mobile first means writing base styles for small screens and adding min-width queries for larger ones.
  • <meta name="viewport" content="width=device-width, initial-scale=1"> is the recommended setting; disabling zoom harms accessibility.
  • max-width: 100% makes images and video shrink with their container.
  • For iframes, wrap the embed in a box with padding-bottom: 56.25% for a 16:9 ratio and position the frame inside it.

Practice Tip: Take any fixed-width page, switch its columns to percentages, add the viewport meta tag and drag the browser window narrower. Add a query only at the width where text first becomes uncomfortable to read.

Common Mistake: Forgetting the viewport meta tag, so phones render the page at a wide virtual size and ignore your media queries.

Important Questions:

  • What does mobile first mean? You write the base CSS for small screens and use min-width media queries to add layout for larger screens, so phones download only the base styles.
  • How do you calculate a flexible width? Divide the target element width by its context (parent) width and express the result as a percentage.

Course 201, Lesson 5: Preprocessors

Course 201: Advanced HTML & CSS · Difficulty: Hard · Partly dated: Ruby-based tools · Key topics: Haml, Sass and SCSS, variables, nesting, mixins, extend, partials, control directives

Lesson 5 introduces preprocessors, tools that turn a friendlier language into HTML or CSS. Haml compiles to HTML and Sass compiles to CSS, both on Ruby installed with gem install. The Haml half covers the doctype, indentation-based nesting, classes and IDs, attributes, comments, filters and Ruby interpolation. The larger Sass half compares the indented Sass syntax with SCSS, then teaches nesting, the parent selector &, variables, interpolation, maths and colour functions, @extend, % selectors that are never compiled themselves, mixins, imports of partial files and the @if, @for, @each and @while directives. It lists alternatives such as LESS, Jade and Slim.

Key Points:

  • A preprocessor compiles one language into another; Haml produces HTML, and Sass or SCSS produces CSS.
  • SCSS looks like normal CSS with extras; the indented Sass syntax drops braces and semicolons.
  • Variables start with $, and #{} interpolates them into selectors and property names.
  • Nesting builds compound selectors, but deep nesting raises specificity, so keep it shallow.
  • @extend shares one selector’s styles; @mixin and @include reuse blocks that take arguments.
  • Partial files joined with @import compile into one stylesheet, so the page makes one request.

Practice Tip: Install a current Sass compiler and write three variables for your site’s colours, then one mixin for a button. Change one variable and recompile to watch every dependent value update.

Common Mistake: Nesting every selector four or five levels deep because Sass allows it. The compiled CSS then has very high specificity that is hard to override.

Important Questions:

  • What is the difference between @extend and a mixin? @extend makes selectors share one rule set; a mixin copies its declarations wherever it is included and can accept arguments.
  • What is the difference between Sass and SCSS syntax? Sass uses indentation and no braces or semicolons; SCSS uses braces and semicolons like CSS and accepts plain CSS files.

Course 201, Lesson 6: jQuery

Course 201: Advanced HTML & CSS · Difficulty: Medium · Partly dated: jQuery 1.9 era and var-based JavaScript · Key topics: JavaScript basics, jQuery object, selectors, traversing, manipulation, events, effects

Because jQuery was everywhere when this lesson was written, it teaches JavaScript through it. It first introduces JavaScript as the behaviour layer on top of HTML and CSS: loading a script, values, var variables, statements, functions, arrays and objects. It then installs jQuery from a local file or CDN (the example is version 1.9.0) and explains the $ object and document ready. After that come CSS-style selectors, traversing methods, getting and setting attributes, styles and DOM content, events with .on(), and effects such as fading and sliding with duration, easing and callbacks. Demos include a closable notice and tabs.

Key Points:

  • JavaScript adds behaviour to the structure (HTML) and presentation (CSS) layers; load scripts just before the closing </body> tag when possible.
  • Value types include strings, Booleans, numbers, undefined, null, functions and objects; arrays are zero-indexed.
  • The $ symbol selects elements using CSS selectors and returns them so methods can be chained.
  • Wrap code in $(document).ready() so it runs after the page is loaded.
  • The same method gets or sets: .attr('alt') reads, .attr('alt', value) writes.
  • .on(), added in jQuery 1.7, attaches handlers and supports delegation to elements added later.
  • The lesson itself says CSS animations perform better than jQuery effects.

Practice Tip: Make a notice box with a close icon, then write a click handler that removes it, first with a fade-out and then with a callback that deletes the element after the fade.

Common Mistake: Running jQuery code in the head before the elements exist, so the selection is empty and nothing happens. Use document ready, or load the script at the end.

Important Questions:

  • What does $(document).ready() do? It delays your code until the browser has built the DOM, so the elements you select actually exist.
  • How can you chain jQuery methods? Each method returns the selection, so you can add another call straight after, for example .not(".x").parent().

Course 201, Lesson 7: Transforms

Course 201: Advanced HTML & CSS · Difficulty: Medium · Partly dated: browser support statements and prefixes · Key topics: transform syntax, rotate, scale, translate, skew, transform-origin, perspective, 3D transforms, preserve-3d, backface-visibility

The transform property lets you rotate, scale, move and skew elements without changing the document flow. The lesson explains the syntax and vendor-prefix order, then walks through the 2D functions one by one (rotate, scale, translate and skew), how to combine them in one declaration and how transform-origin moves the pivot. It then moves into 3D: the perspective function and property, perspective depth and origin, rotateX, rotateY, scaleZ and translateZ, transform-style: preserve-3d and backface-visibility. Two demos build a cube, first from flat shapes and then in true 3D.

Key Points:

  • Positive rotate() values turn clockwise; the default origin is the element’s centre.
  • List several transform functions in one declaration separated by spaces; a second transform line overwrites the first.
  • translate() moves an element without affecting its neighbours, like relative positioning.
  • transform-origin sets the pivot point; perspective-origin sets where the vanishing point sits.
  • A smaller perspective value gives a stronger 3D effect.
  • transform-style: preserve-3d on a parent keeps nested children in 3D space; backface-visibility: hidden hides an element turned away from the viewer.

Practice Tip: Put transform: rotate(20deg) scale(.75) on a box, then reverse the two functions. The result changes because the order of transforms matters.

Common Mistake: Expecting scaleZ() or translateZ() to show anything on a flat page. They need a perspective and another 3D transform before you can see the effect.

Important Questions:

  • What is the difference between transform-origin and perspective-origin? transform-origin is the point an element transforms around; perspective-origin is the position of the viewer’s vanishing point.
  • What does transform-style: preserve-3d do? It lets child elements keep their own 3D positions inside a transformed parent, instead of being flattened into the parent’s plane.

Course 201, Lesson 8: Transitions & Animations

Course 201: Advanced HTML & CSS · Difficulty: Medium · Partly dated: vendor-prefixed keyframes and 2011-era references · Key topics: transition properties, timing functions, delay, shorthand, keyframes, animation properties, fill mode, play state

This lesson separates two ideas. A transition smooths the change between two states, such as a hover, and has four properties: transition-property, -duration, -timing-function and -delay, plus a shorthand. It explains which properties can transition (those with an in-between value, so not display) and the timing keywords, cubic-bezier() and steps(). Animations then add @keyframes with several waypoints, along with animation-name, duration, iteration count, direction, play state and fill mode. A pressable button and a flipping two-sided card are the main demos.

Key Points:

  • A transition needs a state change (such as :hover) and different styles in each state.
  • Only properties with an intermediate value can transition; display cannot.
  • The transition shorthand order is property, duration, timing function, delay.
  • @keyframes define waypoints with percentages or from and to; animation-duration is required for it to run.
  • animation-iteration-count accepts a number or infinite; animation-direction: alternate plays forwards then backwards.
  • animation-fill-mode: forwards keeps the last keyframe’s styles after the animation ends.

Practice Tip: Make a button that moves down 3px and loses its bottom shadow on :active, with a .1s transition. Press it to feel how a tiny transition makes it seem solid.

Common Mistake: Trying to transition display from none to block. Transition opacity or a size instead.

Important Questions:

  • What is the difference between a transition and an animation? A transition moves between two states when something triggers it; an animation can pass through many keyframes and can run on its own.
  • Why can’t display be transitioned? It has no intermediate value between none and block, so the browser cannot calculate steps.

Course 201, Lesson 9: Feature Support & Polyfills

Course 201: Advanced HTML & CSS · Difficulty: Medium · Mostly dated: written around Internet Explorer 6 to 9 · Key topics: fallbacks, HTML5 shiv, Modernizr, feature detection, conditional CSS, polyfills, cross-browser testing

Lesson 9 starts from a sensible principle: a site does not have to look identical in every browser, and each project decides its own level of support based on its traffic. It explains the HTML5 shiv that let Internet Explorer 8 and older style new elements, then Modernizr, which tests for features and adds classes such as cssgradients or no-cssgradients to the html element. You apply styles by class, load files or run scripts conditionally, and use polyfills for missing features. The lesson ends with cross-browser testing using virtual machines for each Internet Explorer version and the IE developer tools.

Key Points:

  • The decision on how far back to support comes from your visitors’ browser statistics and business needs.
  • A polyfill (shiv or shim) is a small script that supplies a feature a browser lacks.
  • Modernizr detects features and adds classes to html, which you use to write separate rules for supported and unsupported cases.
  • Use detection only when a simple fallback will not do, for example a hex colour before an rgba() value needs no detection.
  • Scripts and files can be loaded conditionally, so unsupported browsers get the polyfill and others skip the extra request.
  • The specific tools (IE conditional comments, ievms, Firebug Lite) belong to an era that has ended.

Practice Tip: Write a button with a gradient and a plain-colour fallback, then use a browser setting or a small script to disable the gradient and confirm the fallback still looks acceptable.

Common Mistake: Treating every feature as needing a polyfill. Many features only need a simple fallback layered in the CSS, which avoids extra code and requests.

Important Questions:

  • What is a polyfill? A script that adds a missing browser feature so that code written for the modern feature still works in older browsers.
  • How does Modernizr help with styling? It tests for features and adds matching classes to the html element, so you can write separate rules for supported and unsupported browsers.

Course 201, Lesson 10: Extending Semantics & Accessibility

Course 201: Advanced HTML & CSS · Difficulty: Medium · Key topics: semantic motivation, text-level elements, hidden, microdata, schema.org, WAI-ARIA roles, landmarks

The final lesson argues that semantics and accessibility only pay off when you use them deliberately. It lists the benefits (accessibility, search and globalisation, interoperability), revisits structural elements and prefers the hidden attribute to display: none for content assistive technology should skip. A long section goes through text-level semantics in pairs, such as strong and b, em and i, ins and u, del and s, plus mark, abbr, meter, progress, time, address, code, small and the download and rel link attributes. It then introduces microdata with schema.org, and WAI-ARIA roles, states and properties.

Key Points:

  • Semantics gives content shared, unambiguous meaning for browsers, assistive technology and search engines.
  • The hidden attribute hides content from everyone, including screen readers, while keeping meaning in the markup.
  • abbr with a title gives the full phrase; meter measures a known range and progress shows task completion.
  • Microdata uses itemscope, itemtype and itemprop, with vocabularies from schema.org.
  • WAI-ARIA adds roles (what it is), states (how it is set) and properties through the role attribute and aria-* attributes.
  • banner and contentinfo landmark roles should each appear once per page; the acronym element is deprecated.

Practice Tip: Mark up a contact card as a schema.org Person using itemscope, itemtype and itemprop, then run it through a structured data testing tool to see what search engines read.

Common Mistake: Using ARIA roles to patch non-semantic markup instead of choosing the correct native element first, such as a nav instead of a div with a role.

Important Questions:

  • What is the difference between strong and b? strong marks content of strong importance; b only offsets text stylistically, with no added importance.
  • What is microdata used for? It labels content with a shared vocabulary such as schema.org so search engines can understand it, for example to show business details in results.

How to Study This Book

The 22 lessons are organised as two courses, and the site lets you take them in order. Course 101 (HTML & CSS, lessons 1 to 12) is written for complete beginners and is the part worth doing in full. Course 201 (Advanced HTML & CSS, lessons 1 to 10) assumes you have finished Course 101 and is better treated as a menu than a sequence, for the reasons below. Because the book has fewer than 30 lessons, this page gives each lesson its own block and does not group them.

Start with Course 101, lessons 1 to 3. Lesson 1 sets up your editor, a project folder and the Styles Conference site, which every later beginner lesson extends, so do not skip it even if you have seen HTML before. Lessons 2 and 3 give you the two ideas that cause most beginner bugs: choosing semantic elements, and how the cascade and specificity decide which rule wins. Type every example and keep one project folder going the whole way through.

Lessons 4 and 5 are the hardest beginner material and the ones to repeat. The box model in lesson 4 explains almost every spacing problem you will meet, so use your browser’s developer tools alongside it. Lesson 5 teaches floats and inline-block layouts, which were the standard way to build columns when it was written. Learn them to understand older code, but build new layouts with Flexbox or CSS Grid, which this book does not teach. Lesson 5 only mentions them as emerging specifications.

Lessons 6 to 11 can be read in a looser order once you are through lesson 5. Typography (6) and backgrounds and gradients (7) are about appearance; lists (8), media (9), forms (10) and tables (11) are about the elements you will use on every real page. If your course has a web design assignment, forms and tables are the lessons to rehearse. Lesson 12 is a checklist of habits rather than new syntax, and it is worth reading twice: once now, and again after you have written a few hundred lines of CSS.

In Course 201, read lesson 4 (responsive web design) and lesson 10 (semantics and accessibility) closely, because their core ideas, flexible grids, media queries, mobile-first styles, the viewport tag, semantic elements and ARIA, are still how the web works. Lesson 3 (complex selectors) is also valuable; the selectors themselves are current, so ignore its advice on Internet Explorer shims. Lessons 7 and 8 (transforms, transitions and animations) are good explanations of properties that you still use, but keep the browser-support notes and vendor prefixes in perspective.

Treat the rest of Course 201 as history with a few lasting ideas. Lesson 1 gives you the principles of organising a large stylesheet and reducing requests, but its server setup is Apache-only and its image tools are old. Lesson 2 spends much of its time on Internet Explorer 6 and 7 workarounds. Lesson 5 teaches Sass and Haml through the Ruby tools of its time; learn the language features (variables, nesting, mixins, partials) but install a current Sass compiler instead of the Ruby gem. Lesson 6 teaches JavaScript through jQuery 1.9, so for JavaScript itself use a current text such as the Eloquent JavaScript book linked below. Lesson 9 is mostly about browsers that no longer exist, and you can skip it unless your course covers progressive enhancement.

One honest limit: the lessons end with demos and resource lists, not graded exercises. To test yourself, rebuild the finished Styles Conference site from a blank folder without looking, then redesign it for a different event. That tells you more about your progress than re-reading ever will.


Used In These Programs

This book is used for the Web Technologies and Web Development course in: BS Information Technology · BS Computer Science. Browse all HTML and CSS books, all web development books or all Computer Science books.

Who Should Read This

This book is written for people who have never built a web page. It suits BSIT and BSCS students in a first web technologies, web design or front-end development course, usually in the first or second year, and anyone who needs to learn HTML and CSS before a web programming course. Course 101 needs no earlier programming; Course 201 suits students who want responsive design, selectors and accessibility after the basics. If you already know HTML and CSS, start at Course 201 lessons 3, 4 and 10. It is not the right book if your syllabus is centred on Flexbox, CSS Grid, modern JavaScript or a framework such as React: pair it with Eloquent JavaScript or You Don’t Know JS Yet once the markup and styling are comfortable. If you are new to programming in general, Programming Fundamentals is a good companion.


Applicable Universities

This book is useful for students at Pakistani universities offering BS Information Technology, BS Computer Science and related web technologies and web design courses, including Punjab University, Virtual University, COMSATS, FAST, UET, NUST, and other HEC-recognized institutions.

Official Copy of Learn to Code HTML & CSS

These lessons are free to read on the author’s own site. There is no official PDF, so the legitimate free way to study is online. Click the button below to open the lessons on learn.shayhowe.com, where you can start with Course 101 and move on to the advanced course. The printed book is sold separately.

→ Visit Official Page

FAQs

Is Learn to Code HTML & CSS free?

Yes, the lessons are free to read online at learn.shayhowe.com. The site shows a copyright notice for Shay Howe and does not state an open licence or reuse terms, so this page only links to the lessons and offers original notes. The printed book is sold separately, and the site links to retailers for it.

Is there a PDF of this book?

There is no PDF on the official site. The free version is the set of online lessons, and that is what the button on this page opens. This site does not host or copy any of the lessons.

Which edition is this, and how old is it?

The site does not print an edition number or a revision date. The content refers to Internet Explorer 6 to 9, jQuery 1.9.0 and articles written between about 2010 and 2014, so treat it as material from the early 2010s that has not been rewritten. The print edition is published by New Riders.

How many lessons does it have, and are there exercises?

There are 22 lessons: 12 in Course 101 (HTML & CSS) and 10 in Course 201 (Advanced HTML & CSS). The beginner lessons build one running project, the Styles Conference website, with demos and source code to compare against, but there are no graded end-of-lesson exercises.

Is it good for complete beginners?

Yes, for Course 101. Lesson 1 starts by explaining what HTML and CSS are and builds a first page in a plain text editor, so no earlier programming is needed. Course 201 assumes you have finished Course 101 and is noticeably harder, especially the Sass and jQuery lessons.

Is it still current in 2026, and does it cover Flexbox, Grid or modern JavaScript?

The core of Course 101 is still correct: elements, the cascade, the box model, forms, tables and clean coding habits. But the layout lesson uses floats and inline-block columns, and no lesson teaches Flexbox or CSS Grid. In Course 201, the responsive design, selectors and accessibility lessons hold up well, while the lessons on Internet Explorer fixes, Ruby-based Sass and Haml, jQuery 1.9 and polyfills are largely historical. Learn current layout and JavaScript from a modern text.

Related Books

Learn to Code HTML & CSS is still a clear, friendly way to start web development, as long as you treat Course 101 as the foundation and the advanced course as a mix of lasting ideas and history. Rebuild the conference website from a blank folder, learn Flexbox and Grid elsewhere, and move on to JavaScript. Browse more Computer Science books for the rest of your semester.

Learn to Code HTML & CSS and Learn to Code Advanced HTML & CSS by Shay Howe. © Shay Howe. Print edition: New Riders. Official source: https://learn.shayhowe.com/. This page links to the official site and does not host or copy the lessons.

Leave a Comment