Summary
HTML (HyperText Markup Language) is the foundational markup language for creating web pages and web applications. It provides the semantic structure for content, defining elements like headings, paragraphs, links, images, and forms. Modern HTML5 introduces semantic elements, multimedia support, and APIs that enhance web functionality. Understanding HTML is essential for web development, as it forms the backbone of every website and works in conjunction with CSS for styling and JavaScript for interactivity. This cheatsheet covers HTML fundamentals, semantic markup, accessibility, and best practices for technical interviews.
HTML Basics
What is HTML?
- HyperText Markup Language - standard markup language for web pages
- Uses tags to structure content
- Not a programming language, but a markup language
Basic Syntax
<tagname attribute="value">Content</tagname>
<!-- Self-closing tag -->
<img src="image.jpg" alt="Description" />
Document Structure
Basic HTML5 Template
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Page Title</title>
</head>
<body>
<!-- Content goes here -->
</body>
</html>
Key Structure Elements
<!DOCTYPE html>- Declares HTML5 document<html>- Root element<head>- Metadata container<body>- Visible content container
Common Elements
Text Elements
<h1> to <h6> <!-- Headings (h1 largest) -->
<p> <!-- Paragraph -->
<br> <!-- Line break -->
<hr> <!-- Horizontal rule -->
<strong> <!-- Important text (bold) -->
<em> <!-- Emphasized text (italic) -->
<mark> <!-- Highlighted text -->
<del> <!-- Deleted text -->
<ins> <!-- Inserted text -->
<sub> <!-- Subscript -->
<sup> <!-- Superscript -->
Links and Navigation
<!-- External link -->
<a href="https://example.com" target="_blank">Link</a>
<!-- Internal link -->
<a href="#section">Jump to section</a>
<!-- Email link -->
<a href="mailto:email@example.com">Email</a>
<!-- Download link -->
<a href="file.pdf" download>Download PDF</a>
Lists
<!-- Unordered list -->
<ul>
<li>Item 1</li>
<li>Item 2</li>
</ul>
<!-- Ordered list -->
<ol type="1|A|a|I|i">
<li>First</li>
<li>Second</li>
</ol>
<!-- Description list -->
<dl>
<dt>Term</dt>
<dd>Definition</dd>
</dl>
Semantic HTML5
Structural Elements
<header> <!-- Page/section header -->
<nav> <!-- Navigation links -->
<main> <!-- Main content (one per page) -->
<article> <!-- Self-contained content -->
<section> <!-- Thematic grouping -->
<aside> <!-- Sidebar/related content -->
<footer> <!-- Page/section footer -->
<figure> <!-- Self-contained media -->
<figcaption> <!-- Caption for figure -->
Why Semantic HTML?
- Better SEO
- Improved accessibility
- Clearer code structure
- Better for screen readers
Forms and Inputs
Basic Form Structure
<form action="/submit" method="POST">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required>
<button type="submit">Submit</button>
</form>
Input Types
<!-- Text inputs -->
<input type="text" placeholder="Enter text">
<input type="password">
<input type="email">
<input type="tel">
<input type="url">
<input type="search">
<!-- Number inputs -->
<input type="number" min="0" max="100" step="5">
<input type="range" min="0" max="100">
<!-- Date/Time inputs -->
<input type="date">
<input type="time">
<input type="datetime-local">
<!-- Selection inputs -->
<input type="checkbox" checked>
<input type="radio" name="group" value="option1">
<!-- File input -->
<input type="file" accept="image/*" multiple>
<!-- Other inputs -->
<input type="color">
<input type="hidden" value="secret">
Other Form Elements
<!-- Textarea -->
<textarea rows="4" cols="50"></textarea>
<!-- Select dropdown -->
<select name="options">
<option value="1">Option 1</option>
<option value="2" selected>Option 2</option>
<optgroup label="Group">
<option value="3">Option 3</option>
</optgroup>
</select>
<!-- Datalist (input with suggestions) -->
<input list="browsers">
<datalist id="browsers">
<option value="Chrome">
<option value="Firefox">
</datalist>
Form Attributes
action- Where to send form datamethod- HTTP method (GET/POST)enctype- Encoding type (for file uploads:multipart/form-data)novalidate- Disable browser validation
Media Elements
Images
<img src="image.jpg"
alt="Description"
width="300"
height="200"
loading="lazy">
<!-- Responsive images -->
<picture>
<source media="(min-width: 800px)" srcset="large.jpg">
<source media="(min-width: 400px)" srcset="medium.jpg">
<img src="small.jpg" alt="Description">
</picture>
Audio & Video
<!-- Audio -->
<audio controls>
<source src="audio.mp3" type="audio/mpeg">
<source src="audio.ogg" type="audio/ogg">
Your browser doesn't support audio.
</audio>
<!-- Video -->
<video controls width="320" height="240" poster="thumbnail.jpg">
<source src="video.mp4" type="video/mp4">
<source src="video.webm" type="video/webm">
<track src="subtitles.vtt" kind="subtitles" srclang="en">
</video>
Embedding Content
<!-- Iframe -->
<iframe src="https://example.com"
width="600"
height="400"
sandbox="allow-scripts">
</iframe>
<!-- Embed -->
<embed src="file.pdf" type="application/pdf" width="500" height="600">
<!-- Object -->
<object data="file.pdf" type="application/pdf">
<p>PDF cannot be displayed</p>
</object>
Tables
Basic Table Structure
<table>
<caption>Table Caption</caption>
<thead>
<tr>
<th scope="col">Header 1</th>
<th scope="col">Header 2</th>
</tr>
</thead>
<tbody>
<tr>
<td>Data 1</td>
<td>Data 2</td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="2">Footer</td>
</tr>
</tfoot>
</table>
Table Attributes
colspan- Cell spans multiple columnsrowspan- Cell spans multiple rowsscope- Specifies header cell scope (col/row)
Metadata and SEO
Essential Meta Tags
<!-- Character encoding -->
<meta charset="UTF-8">
<!-- Viewport for responsive design -->
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- Page description -->
<meta name="description" content="Page description (150-160 chars)">
<!-- Keywords (less important now) -->
<meta name="keywords" content="keyword1, keyword2">
<!-- Author -->
<meta name="author" content="John Doe">
<!-- Robots -->
<meta name="robots" content="index, follow">
Open Graph (Social Media)
<meta property="og:title" content="Page Title">
<meta property="og:description" content="Page description">
<meta property="og:image" content="https://example.com/image.jpg">
<meta property="og:url" content="https://example.com/page">
<meta property="og:type" content="website">
Favicon
<link rel="icon" type="image/x-icon" href="/favicon.ico">
<link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png">
<link rel="apple-touch-icon" href="/apple-touch-icon.png">
Accessibility (a11y)
ARIA Attributes
<!-- Landmarks -->
<nav role="navigation" aria-label="Main navigation">
<!-- Live regions -->
<div aria-live="polite" aria-atomic="true">
<!-- States -->
<button aria-pressed="false">Toggle</button>
<div aria-hidden="true">Hidden from screen readers</div>
<!-- Relationships -->
<input aria-describedby="help-text">
<span id="help-text">Helper text</span>
Accessibility Best Practices
Always use alt text for images
<img src="chart.jpg" alt="Sales increased 25% in Q3">Use semantic HTML
<!-- Good --> <button>Click me</button> <!-- Bad --> <div onclick="...">Click me</div>Label form inputs
<label for="email">Email:</label> <input type="email" id="email" name="email">Provide skip links
<a href="#main" class="skip-link">Skip to main content</a>
HTML5 APIs
Local Storage
<script>
// Store data
localStorage.setItem('key', 'value');
// Retrieve data
const value = localStorage.getItem('key');
// Remove data
localStorage.removeItem('key');
</script>
Geolocation
<script>
navigator.geolocation.getCurrentPosition(
position => console.log(position.coords),
error => console.error(error)
);
</script>
Canvas
<canvas id="myCanvas" width="200" height="100"></canvas>
<script>
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
ctx.fillStyle = 'red';
ctx.fillRect(10, 10, 50, 50);
</script>
Data Attributes
<div data-user-id="123" data-role="admin">
<script>
// Access in JavaScript
const div = document.querySelector('div');
console.log(div.dataset.userId); // "123"
console.log(div.dataset.role); // "admin"
</script>
Best Practices
1. Use Semantic HTML
<!-- Good -->
<nav>
<ul>
<li><a href="/">Home</a></li>
</ul>
</nav>
<!-- Bad -->
<div class="navigation">
<div class="nav-item">Home</div>
</div>
2. Validate Your HTML
- Use W3C Validator
- Ensure proper nesting
- Close all tags
3. Optimize Performance
<!-- Lazy load images -->
<img src="image.jpg" loading="lazy">
<!-- Preload critical resources -->
<link rel="preload" href="font.woff2" as="font">
<!-- Defer non-critical scripts -->
<script src="script.js" defer></script>
4. Mobile-First Approach
<meta name="viewport" content="width=device-width, initial-scale=1.0">
5. Progressive Enhancement
- Start with basic HTML
- Add CSS for styling
- Add JavaScript for enhancement
Key Interview Concepts
Block vs Inline Elements
| Property | Block Elements | Inline Elements | Inline-Block |
|---|---|---|---|
| Width | Full container width | Content width only | Content width |
| Line Break | Before and after | No line break | No line break |
| Width/Height | Can set | Cannot set | Can set |
| Margins/Padding | All sides work | Only horizontal | All sides work |
| Examples | <div>, <p>, <h1> |
<span>, <a>, <strong> |
<img>, <button> |
Document Object Model (DOM)
Definition: Programming interface for HTML documents
Document
└── html
├── head
│ ├── title
│ └── meta
└── body
├── header
├── main
└── footer
ID vs Class Attributes
| Aspect | ID | Class |
|---|---|---|
| Uniqueness | Must be unique per page | Can be reused |
| CSS Selector | #idname |
.classname |
| Specificity | Higher (100) | Lower (10) |
| JavaScript | getElementById() |
getElementsByClassName() |
| Use Case | Unique elements, anchors | Styling groups, reusable styles |
Void Elements (Self-Closing)
Definition: Elements that cannot have content or closing tags
<!-- Common void elements -->
<br> <!-- Line break -->
<hr> <!-- Horizontal rule -->
<img> <!-- Image -->
<input> <!-- Form input -->
<link> <!-- External resource -->
<meta> <!-- Metadata -->
<area> <!-- Image map area -->
<col> <!-- Table column -->
<embed> <!-- External content -->
<source> <!-- Media resource -->
<track> <!-- Text track -->
<wbr> <!-- Line break opportunity -->
DOCTYPE Declaration
Purpose: Instructs browser about HTML version and rendering mode
<!-- HTML5 (current standard) -->
<!DOCTYPE html>
<!-- Legacy versions (rarely used) -->
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <!-- HTML 4.01 Strict -->
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"> <!-- XHTML 1.0 -->
Responsive Design Fundamentals
<!-- Viewport meta tag -->
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- Responsive images -->
<img src="image.jpg" style="max-width: 100%; height: auto;">
<!-- Media queries in CSS -->
Script Loading Strategies
| Attribute | Download | Execution | Use Case |
|---|---|---|---|
| None | Blocks parsing | Immediately | Critical inline scripts |
| async | Parallel | ASAP (interrupts parsing) | Independent scripts (analytics) |
| defer | Parallel | After DOM complete | DOM-dependent scripts |
<!-- Blocking (avoid) -->
<script src="script.js"></script>
<!-- Async (independent scripts) -->
<script async src="analytics.js"></script>
<!-- Defer (DOM manipulation) -->
<script defer src="app.js"></script>
Web Components Architecture
Definition: Suite of technologies for creating reusable custom elements
- Custom Elements: Define new HTML tags
class MyButton extends HTMLElement {
constructor() {
super();
this.innerHTML = `<button>${this.getAttribute('label')}</button>`;
}
}
customElements.define('my-button', MyButton);
- Shadow DOM: Encapsulated DOM and styling
this.attachShadow({ mode: 'open' });
- HTML Templates: Reusable markup
<template id="my-template">
<style>p { color: blue; }</style>
<p>Template content</p>
</template>
Performance Optimization Strategies
Critical Rendering Path:
Minimize Critical Resources
- Inline critical CSS
- Defer non-critical JavaScript
- Preload key resources
Optimize Resource Delivery
<!-- Preload critical resources --> <link rel="preload" href="font.woff2" as="font" crossorigin> <!-- Prefetch future navigation --> <link rel="prefetch" href="/next-page.html"> <!-- DNS prefetch for external domains --> <link rel="dns-prefetch" href="//api.example.com">Image Optimization
<!-- Lazy loading --> <img src="image.jpg" loading="lazy" alt="Description"> <!-- Responsive images --> <img srcset="small.jpg 500w, medium.jpg 1000w, large.jpg 2000w" sizes="(max-width: 600px) 500px, (max-width: 1200px) 1000px, 2000px" src="medium.jpg" alt="Responsive image">
Quick Reference
HTML Entities
< <!-- < -->
> <!-- > -->
& <!-- & -->
" <!-- " -->
' <!-- ' -->
<!-- Non-breaking space -->
© <!-- © -->
® <!-- ® -->
Global Attributes
id- Unique identifierclass- CSS class(es)style- Inline CSStitle- Tooltip textdata-*- Custom data attributeshidden- Hide elementtabindex- Tab ordercontenteditable- Editable contentdir- Text direction (ltr/rtl)lang- Language code
Event Attributes
onclick- Mouse clickonsubmit- Form submissiononchange- Value changeonfocus- Element focusedonblur- Element loses focusonload- Page/element loaded
HTML5 Semantic Elements Benefits
SEO Impact:
- Search engines better understand content structure
- Improved content hierarchy recognition
- Better rich snippets in search results
Accessibility Benefits:
- Screen readers navigate more efficiently
- Landmark roles automatically applied
- Better keyboard navigation support
Code Maintainability:
- Self-documenting structure
- Clearer developer intent
- Easier to understand and modify
Interview Preparation Checklist
- ✅ Document Structure: DOCTYPE, head, body, meta tags
- ✅ Semantic Elements: header, nav, main, article, section, aside, footer
- ✅ Forms: Input types, validation, accessibility
- ✅ Media: Images, audio, video, responsive techniques
- ✅ Tables: Proper structure, accessibility with scope
- ✅ SEO: Meta tags, Open Graph, structured data
- ✅ Accessibility: ARIA, alt text, semantic markup
- ✅ Performance: Lazy loading, preloading, async/defer
- ✅ HTML5 APIs: Storage, Geolocation, Canvas
- ✅ Best Practices: Validation, security, progressive enhancement
Key Takeaway: HTML is more than just markup—it's about creating semantic, accessible, and performant web content. Focus on understanding not just what elements to use, but why and when to use them for optimal user experience and maintainability.