HTML

Complete HTML cheat sheet covering document structure, semantic elements, forms, media, accessibility, and common interview traps.

14 sections21 cards

Bare minimum HTML file

Every HTML file should start with a doctype declaration — it tells the browser to use modern standards mode. Without it, browsers fall into "quirks mode" and render things inconsistently.

<!DOCTYPE html> then <html lang="en"> wraps everything. Inside, <head> holds metadata (not visible) and <body> holds content (visible).

<meta charset="UTF-8"> — always include this first inside head. It makes sure special characters (é, ₹, →) render correctly.

<meta name="viewport" content="width=device-width, initial-scale=1"> — makes the page responsive on mobile. Without this, mobile browsers zoom out and show a desktop-sized layout.

layout

<header> — top of page or section. Logos, nav, hero.

<nav> — navigation links. Can be in header or standalone.

<main> — primary content. Only one per page.

<aside> — sidebar, related content, ads.

<footer> — bottom of page. Links, copyright.

<section> — thematic group of content. Has a heading.

<article> — self-contained piece (blog post, card). Makes sense on its own.

text-level

<h1> to <h6> — headings. Only one h1 per page (SEO). Don't skip levels.

<p> — paragraph. Block element.

<strong> — important text (bold + semantic). Vs <b> which is just visual.

<em> — emphasis (italic + semantic). Vs <i> which is just visual.

<small> — fine print, captions.

<mark> — highlighted/relevant text.

<time datetime="2024-01-01"> — machine-readable dates.

<abbr title="HyperText">HTML</abbr> — abbreviations with tooltip.

Block elements — always start on a new line, take full width. Examples: div, p, h1-h6, ul, ol, li, section, article, header, footer, form, table

Inline elements — flow within text, only take needed width. Examples: span, a, strong, em, img, input, label, button, code

Inline-block — flows like inline but respects width/height. This is a CSS concept but important here — images behave this way by default.

⚠️ You cannot put a block element inside an inline element. <a><div>...</div></a> is invalid HTML (though browsers may still render it).

<a href="..."> — the anchor tag. The href attribute defines where it goes.

Types of href values:

· Absolute URL: https://google.com

· Relative path: ./about.html or /contact

· Same-page anchor: #section-id

· Email: mailto:hi@example.com

· Phone: tel:+911234567890

target="_blank" — opens in new tab. Always pair with rel="noopener noreferrer" for security (prevents the new tab from accessing your page via window.opener).

download attribute — forces download instead of navigation: <a href="/file.pdf" download>

types

<ul> — unordered list (bullets). Use when order doesn't matter.

<ol> — ordered list (numbers). Use for steps, rankings.

<dl> — description list. Key-value pairs. <dt> is term, <dd> is definition.

Lists can be nested — <ul> inside a <li>.

ol attributes

type="1|a|A|i|I" — numbering style.

start="5" — start from a specific number.

reversed — counts down.

Individual <li value="3"> overrides position.

Images

alt attribute is mandatory — describes image for screen readers and when image fails to load. Empty alt="" for decorative images (tells screen reader to skip it).

width and height attributes — set these to prevent layout shift (CLS). Browser reserves space before image loads.

loading="lazy" — defers loading until image is near viewport. Great for performance below the fold.

<figure> + <figcaption> — semantic wrapper for image with caption.

Use tables for tabular data only — not for layout (that's a legacy anti-pattern).

Structure: <table><thead>, <tbody>, <tfoot><tr> (row) → <th> (header cell) or <td> (data cell).

<th scope="col"> or scope="row" — accessibility attribute. Tells screen readers what the header is for.

colspan and rowspan — merge cells across columns or rows.

<caption> — table title. Goes right after opening <table> tag. Better than a heading above the table semantically.

Form basics

action — where data is sent. method="GET|POST" — GET appends to URL (good for search), POST sends in body (good for sensitive data, mutations).

enctype="multipart/form-data" — required when uploading files.

novalidate — disables browser's built-in validation. Useful when you handle validation in JS yourself.

input types

text | email | password | number | tel | url | search | date | time | datetime-local | color | range | file | checkbox | radio | hidden | submit | reset

Type matters — mobile shows correct keyboard (email shows @, tel shows numpad). Browsers also validate format (email checks for @).

key attributes

name — key used when submitting form. Required for data to be sent.

id — used to link with <label for="id">.

required — browser blocks submit if empty.

placeholder — hint text inside input. Not a replacement for labels.

disabled — not editable, not submitted.

readonly — not editable, but still submitted.

autocomplete="off" — prevents browser from suggesting saved values.

min, max, step — for number/range/date inputs.

pattern — regex for validation. E.g. pattern="[0-9]{10}"

maxlength, minlength — character limits.

multiple — allows multiple values (file, email inputs, select).

accept=".pdf,.jpg" — file types for file input.

other form elements

<textarea rows="4"> — multiline text. Resizable by default.

<select> + <option> — dropdown. multiple makes it a list. <optgroup label> groups options.

<button type="submit|reset|button"> — default type is submit inside a form. Always specify type to avoid accidental submits.

<fieldset> + <legend> — groups related inputs. Legend is the group label. Great for radio groups.

<datalist id="..."> — provides autocomplete suggestions for a text input. Link via <input list="id">.

<output> — displays result of a calculation.

label — critical

Always label your inputs. Two ways:

1. <label for="email"> + <input id="email"> — linked by matching id.

2. Wrap input inside label — implicit association, no id needed.

Why it matters: clicking the label focuses the input. Screen readers announce the label when input is focused. Skipping labels fails accessibility.

placeholder is NOT a label substitute — it disappears when user types.

<title> — shown in browser tab and search engine results. Very important for SEO.

<meta name="description"> — shown in search result snippets. 150-160 chars recommended.

<link rel="stylesheet" href="..."> — links external CSS. Goes in head.

<link rel="icon" href="favicon.ico"> — page icon in browser tab.

<link rel="canonical" href="..."> — tells search engines the "main" URL when the same content is accessible from multiple URLs.

<meta property="og:title"> — Open Graph tags. Control how your page looks when shared on Twitter, LinkedIn, WhatsApp. Key ones: og:title, og:description, og:image, og:url.

<script> — put at end of <body> or use defer/async in head. Without these, script blocks HTML parsing.

defer — downloads in parallel, runs after HTML is fully parsed. Use this most of the time.

async — downloads in parallel, runs immediately when ready. Blocks parsing briefly. Use for independent scripts (analytics).

alt on images, label on inputs, lang on html — the bare minimum.

ARIA attributes — used when native HTML isn't enough:

role="..." — tells assistive tech what an element is. E.g. role="button" on a div acting as a button.

aria-label="..." — accessible name for elements with no visible text (icon buttons).

aria-labelledby="id" — points to another element as the label.

aria-hidden="true" — hides from screen readers (decorative icons).

aria-expanded, aria-selected, aria-checked — dynamic states for custom widgets.

Keyboard nav — all interactive elements must be focusable and operable via keyboard. Native elements (button, a, input) handle this automatically. Custom elements need tabindex="0" and key handlers.

tabindex="0" — adds element to natural tab order. tabindex="-1" — focusable by JS only, not by tabbing.

<iframe src="..." title="..."> — embeds another page inside your page. title is required for accessibility.

sandbox attribute — restricts what the iframe can do. E.g. sandbox="allow-scripts allow-same-origin". Without sandbox, iframe has full JS access.

loading="lazy" — defers iframe loading.

allow="camera; microphone" — permissions for embedded content.

Modern alternative: most platforms (YouTube, Maps) give you embed codes. Just use those.

id | class | style | hidden | tabindex | contenteditable | draggable | spellcheck | title | lang | dir | data-*

data-* — custom data attributes. Store extra info on elements. Access in JS via element.dataset.name. Very useful for passing data to JS without hidden inputs.

contenteditable="true" — makes any element editable in the browser. Basis for rich text editors.

hidden — hides element (equivalent to display:none). Different from visibility:hidden.

title — tooltip on hover. On abbr it shows the full form.

traps

· <img>, <input>, <br>, <hr>, <meta>, <link> are void elements — no closing tag needed (though /> is fine).

· <b> vs <strong> — both bold visually but strong carries importance semantics. Same with <i> vs <em>.

· Default button type inside form is submit. A plain <button> will submit the form.

· disabled inputs are not included in form submission. readonly inputs are.

· IDs must be unique on the page. Class can repeat. IDs are used for labels, anchors, JS targeting.

good to know

· HTML is parsed top to bottom. Scripts without defer block parsing at that point.

· <noscript> — shown when JS is disabled. Good for fallback messages.

· <template> — HTML not rendered but accessible via JS. Used in web components.

· <dialog> — native modal element. Has built-in .showModal() and .close() JS methods. Handles focus trap and ESC key natively.

· <details> + <summary> — native accordion. No JS needed.

· <progress value="70" max="100"> and <meter> — native progress and gauge elements.

These are JS APIs that HTML5 introduced. Know they exist even if you don't use them daily:

localStorage / sessionStorage — key-value storage in browser. Local persists, session clears on tab close.

Geolocation APInavigator.geolocation.getCurrentPosition()

Drag and Drop API — native drag events (dragstart, dragover, drop). draggable="true" on element.

Canvas API<canvas> element + JS 2D drawing. Used for charts, games.

Web Workers — run JS in background thread. Doesn't block UI.

History APIpushState, replaceState. How SPAs handle routing without page reload.

Intersection Observer — detect when element enters viewport. Lazy load, infinite scroll.