DEV SCRIPTS

Html Code FAQs

HTML5 Interview FAQ
HTML5 Basics

HTML5 is the fifth major revision of the HyperText Markup Language, standardized by the W3C and WHATWG. Its primary goals over HTML4 were: reducing the need for browser plugins like Flash, providing native multimedia support, introducing semantic meaning to page structure, enabling powerful offline and client-side storage capabilities, and defining cleaner error-handling rules so all browsers behave consistently.

Key improvements: new semantic elements, <audio>/<video>, Canvas 2D/3D, Web Storage, Web Workers, Geolocation, WebSockets, and a standardized DOCTYPE.

html
<!-- HTML4 doctype — verbose -->
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
  "http://www.w3.org/TR/html4/loose.dtd">

<!-- HTML5 doctype — simple -->
<!DOCTYPE html>

<!-- HTML5 charset declaration -->
<meta charset="UTF-8">

An element is a building block of an HTML document defined by a start tag, optional content, and an end tag. An attribute is additional information placed inside the opening tag that modifies the element’s behavior or appearance. Attributes always come in name-value pairs and must be in the opening tag only.

html
<!-- Element: <a>, Attributes: href, target, rel -->
<a href="https://example.com" target="_blank" rel="noopener">
  Visit Example
</a>

<!-- Void element — no closing tag needed -->
<img src="logo.png" alt="Logo" width="200" height="80">

<!-- Boolean attribute — presence = true -->
<input type="checkbox" checked disabled>

<!-- Data attributes — custom metadata -->
<div data-user-id="42" data-role="admin">Profile</div>

Block-level elements start on a new line, take up the full available width, and can contain other block-level or inline elements. Inline elements flow within text, only take as much width as needed, and cannot contain block-level elements. HTML5 replaced this binary model with a richer content category system, but the distinction remains important for CSS layout.

html
<!-- Block-level: div, p, h1-h6, ul, ol, li, table, section, article -->
<div>I take the full width of my parent.</div>
<p>I start on a new line.</p>

<!-- Inline: span, a, strong, em, img, input, label -->
<p>This is <strong>bold</strong> and <em>italic</em> text.</p>

<!-- Invalid: block inside inline -->
<span><div>Wrong!</div></span>  <!-- ⚠️ -->

<!-- Valid: inline inside block -->
<p><span>Correct.</span></p>  <!-- ✓ -->

Void elements are elements that cannot have any child content and therefore have no closing tag. In HTML5 you must not write a closing tag for them (unlike XHTML where /> was required). There are exactly 14 void elements in HTML5.

html
<!-- The 14 HTML5 void elements -->
<area>
<base>
<br>
<col>
<embed>
<hr>
<img src="photo.jpg" alt="A photo">
<input type="text" name="username">
<link rel="stylesheet" href="style.css">
<meta charset="UTF-8">
<param name="autoplay" value="true">
<source src="video.mp4" type="video/mp4">
<track kind="subtitles" src="subs.vtt">
<wbr>

<!-- HTML5: no self-closing slash needed -->
<br>   <!-- correct ✓ -->
<br/>  <!-- allowed but unnecessary -->

An id must be unique within the entire page — only one element can have a given id. It is used for direct element access via JavaScript (getElementById) and as anchor link targets. A class can be shared by many elements and an element can have multiple classes. Classes are the primary CSS styling hook and are used for grouping related elements.

html
<!-- id: unique, one per page -->
<header id="site-header">...</header>

<!-- Anchor target -->
<a href="#site-header">Back to top</a>

<!-- class: reusable, multiple allowed -->
<div class="card featured large">...</div>
<div class="card">...</div>
<div class="card">...</div>

<!-- JS access -->
<script>
  document.getElementById("site-header");       // one element
  document.querySelectorAll(".card");           // all cards
</script>
Semantic Elements

Semantic elements clearly describe their meaning to both the browser and the developer — the tag name itself communicates the role of the content. Before HTML5, developers used <div> and <span> for everything; semantic elements like <article>, <nav>, and <footer> make the structure self-documenting. Benefits: better accessibility (screen readers), improved SEO, and easier maintenance.

html
<!-- Non-semantic (HTML4 style) -->
<div id="header">...</div>
<div id="nav">...</div>
<div id="main">...</div>
<div id="footer">...</div>

<!-- Semantic (HTML5) -->
<header>...</header>
<nav>...</nav>
<main>
  <article>
    <section>...</section>
  </article>
  <aside>...</aside>
</main>
<footer>...</footer>

<article> represents self-contained content that could be distributed independently — a blog post, news article, or forum post. <section> groups thematically related content within a document and should typically have a heading. <div> is a generic, non-semantic container used purely for styling or scripting when no semantic element fits.

html
<main>
  <!-- article: could stand alone as an RSS feed item -->
  <article>
    <h2>Getting Started with HTML5</h2>

    <!-- section: chapter/topic within the article -->
    <section>
      <h3>New Semantic Elements</h3>
      <p>...</p>
    </section>

    <section>
      <h3>Forms</h3>
      <p>...</p>
    </section>
  </article>

  <!-- div: no semantic meaning, just layout grouping -->
  <div class="ad-banner">...</div>
</main>

These are the core page-structure elements of HTML5. <header> and <footer> can appear multiple times — once for the page, and again inside each <article> or <section>. <main> must appear only once and wraps the central unique content. <aside> holds content tangentially related to its context (sidebars, pull quotes). <nav> marks major navigation blocks.

html
<body>
  <header>                    <!-- site header -->
    <nav>                     <!-- primary navigation -->
      <a href="/">Home</a>
      <a href="/blog">Blog</a>
    </nav>
  </header>

  <main>                      <!-- unique page content (once only) -->
    <article>
      <header>                <!-- article header (allowed) -->
        <h1>My Post</h1>
      </header>
      <p>Content...</p>
    </article>

    <aside>                   <!-- related sidebar -->
      <h2>Related Posts</h2>
    </aside>
  </main>

  <footer>© 2024</footer>    <!-- site footer -->
</body>

<figure> wraps self-contained content that is referenced from the main text but could be moved without affecting the flow — diagrams, photos, code listings, or charts. <figcaption> provides an optional caption and must be the first or last child of <figure>. Together they create a semantic association between media and its description.

html
<figure>
  <img src="chart.png" alt="Sales chart for Q3 2024">
  <figcaption>Fig 1 — Q3 2024 sales grew 18% over Q2.</figcaption>
</figure>

<!-- Works for code blocks too -->
<figure>
  <pre><code>const x = 42;</code></pre>
  <figcaption>Listing 3 — Variable declaration</figcaption>
</figure>

<!-- Works for video -->
<figure>
  <video src="demo.mp4" controls></video>
  <figcaption>Product demo walkthrough (2:34)</figcaption>
</figure>
Forms & Input Types

HTML5 added 13 new input types that trigger native browser UI (date pickers, color swatches, sliders) and built-in validation. Unsupported browsers gracefully degrade to type="text". Using the correct type also improves the mobile experience by triggering the right keyboard (numeric, email, URL, etc.).

html
<!-- Date / time -->
<input type="date">
<input type="time">
<input type="datetime-local">
<input type="month">
<input type="week">

<!-- Contact / URLs -->
<input type="email" placeholder="you@example.com">
<input type="url" placeholder="https://">
<input type="tel" placeholder="+1 555 000 0000">

<!-- Numeric -->
<input type="number" min="0" max="100" step="5">
<input type="range" min="0" max="10" value="5">

<!-- Other -->
<input type="color" value="#7B2FBE">
<input type="search" placeholder="Search...">

HTML5 added powerful form attributes that reduce the need for JavaScript validation. Key additions: required, placeholder, autofocus, autocomplete, pattern (regex validation), min/max/step, multiple, novalidate, and form (to associate an input with a form by ID even if outside it).

html
<form id="signup" novalidate>
  <!-- required + placeholder -->
  <input type="email" required placeholder="Email address">

  <!-- autofocus: focuses on page load -->
  <input type="text" name="name" autofocus>

  <!-- pattern: regex validation -->
  <input type="text" pattern="[A-Za-z]{3,}"
         title="At least 3 letters">

  <!-- min / max / step -->
  <input type="number" min="18" max="120" step="1">

  <!-- multiple: accept several emails -->
  <input type="email" multiple>
</form>

<!-- form attribute: input outside the <form> tag -->
<input type="text" name="extra" form="signup">

<datalist> provides a list of predefined options for an <input> field, creating a native autocomplete dropdown. Unlike <select>, the user can still type any value freely — the datalist just offers suggestions. Link them with the list attribute on the input matching the datalist’s id.

html
<label for="browser">Choose your browser:</label>
<input type="text" id="browser" list="browsers"
       placeholder="Start typing...">

<datalist id="browsers">
  <option value="Chrome">
  <option value="Firefox">
  <option value="Safari">
  <option value="Edge">
  <option value="Opera">
</datalist>

<!-- Works with number and range inputs too -->
<input type="range" list="markers" min="0" max="100">
<datalist id="markers">
  <option value="0">
  <option value="25">
  <option value="50">
  <option value="75">
  <option value="100">
</datalist>

GET appends form data to the URL as a query string — it is visible, bookmarkable, and cached. Use it for search forms and non-sensitive, idempotent requests. POST sends data in the request body — it is not visible in the URL, not cached, and supports large payloads and file uploads. Use it for login forms, sign-up, and any action that modifies server state.

html
<!-- GET: data in URL → /search?q=html5&lang=en -->
<form action="/search" method="GET">
  <input type="search" name="q">
  <select name="lang">
    <option value="en">English</option>
  </select>
  <button>Search</button>
</form>

<!-- POST: data in request body, not visible in URL -->
<form action="/register" method="POST">
  <input type="email" name="email" required>
  <input type="password" name="password" required>
  <button type="submit">Sign Up</button>
</form>

<!-- File uploads require POST + multipart encoding -->
<form method="POST" enctype="multipart/form-data">
  <input type="file" name="avatar">
</form>
Multimedia — Audio & Video

HTML5 provides native <video> and <audio> elements — no plugins required. Use multiple <source> children to supply different formats for cross-browser support; the browser picks the first format it can play. Always provide a fallback message for very old browsers.

html
<!-- Video with multiple formats -->
<video width="640" height="360" controls poster="thumbnail.jpg">
  <source src="video.webm" type="video/webm">
  <source src="video.mp4"  type="video/mp4">
  <p>Your browser does not support HTML5 video.</p>
</video>

<!-- Video attributes -->
<video src="clip.mp4" controls autoplay muted loop
       preload="metadata" playsinline></video>

<!-- Audio -->
<audio controls>
  <source src="song.ogg" type="audio/ogg">
  <source src="song.mp3" type="audio/mpeg">
  Your browser does not support audio.
</audio>

<track> adds timed text tracks (subtitles, captions, chapters, descriptions) to <video> and <audio> elements. Tracks use the WebVTT (.vtt) format. The kind attribute declares the track type; default marks it as active by default. This is essential for accessibility compliance (WCAG 2.1).

html
<video src="lecture.mp4" controls>
  <!-- Subtitles: translation of dialogue -->
  <track kind="subtitles" src="subs-en.vtt" srclang="en"
         label="English" default>
  <track kind="subtitles" src="subs-he.vtt" srclang="he"
         label="Hebrew">

  <!-- Captions: subtitles + sound descriptions for deaf users -->
  <track kind="captions" src="captions.vtt" srclang="en">

  <!-- Chapters: navigation points -->
  <track kind="chapters" src="chapters.vtt" srclang="en">
</video>

<!-- subs.vtt file format -->
<!--
WEBVTT

00:00:01.000 --> 00:00:04.000
Hello, welcome to this tutorial.

00:00:05.000 --> 00:00:08.000
Today we cover HTML5 features.
-->
Canvas & SVG

<canvas> is a bitmap drawing surface controlled entirely through JavaScript via a 2D rendering context (or WebGL for 3D). The element itself is just a container — all drawing commands are imperative JavaScript calls. It is used for games, data visualizations, image manipulation, and animations.

html
<canvas id="myCanvas" width="400" height="200">
  Canvas not supported — fallback text here.
</canvas>
javascript
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");

// Draw a filled rectangle
ctx.fillStyle = "#7B2FBE";
ctx.fillRect(10, 10, 200, 80);

// Draw text
ctx.fillStyle = "#fff";
ctx.font = "24px Inter";
ctx.fillText("HTML5 Canvas", 30, 60);

// Draw a circle
ctx.beginPath();
ctx.arc(300, 100, 40, 0, Math.PI * 2);
ctx.strokeStyle = "#F97316";
ctx.lineWidth = 3;
ctx.stroke();

Canvas is a pixel-based (raster) drawing API — once drawn, pixels have no DOM representation and cannot be individually targeted. It performs better for large numbers of objects and per-frame animations. SVG is a vector-based markup format — every shape is a DOM element that can be styled with CSS, selected with JavaScript, and scales perfectly at any size. SVG is better for logos, icons, and interactive charts.

  • Canvas: raster, no DOM nodes per shape, fast for many objects, needs redraw on resize
  • SVG: vector, each shape is a DOM node, CSS-styleable, resolution-independent
html
<!-- SVG: shapes are DOM elements -->
<svg width="200" height="100" xmlns="http://www.w3.org/2000/svg">
  <rect x="10" y="10" width="180" height="80"
        fill="#7B2FBE" rx="8"></rect>
  <text x="100" y="55" text-anchor="middle"
        fill="white" font-size="18">SVG</text>
</svg>

<!-- SVG inline in HTML5 — no namespace needed -->
<svg viewBox="0 0 50 50">
  <circle cx="25" cy="25" r="20" fill="#F97316"></circle>
</svg>
Web Storage & Offline

HTML5 Web Storage provides two mechanisms — localStorage and sessionStorage — for storing key-value string pairs in the browser. Compared to cookies: storage is larger (~5–10 MB vs ~4 KB), data is not sent with every HTTP request (no network overhead), and access is only via JavaScript (no Set-Cookie header). Cookies remain necessary for server-side session management.

javascript
// localStorage — persists until explicitly cleared
localStorage.setItem("theme", "dark");
localStorage.getItem("theme");         // "dark"
localStorage.removeItem("theme");
localStorage.clear();                  // remove all

// sessionStorage — cleared when tab closes
sessionStorage.setItem("token", "abc123");
sessionStorage.getItem("token");       // "abc123"

// Storing objects — must serialize to JSON
const user = { name: "Ana", role: "admin" };
localStorage.setItem("user", JSON.stringify(user));
const stored = JSON.parse(localStorage.getItem("user"));

// Listen for changes from other tabs
window.addEventListener("storage", function(e) {
  console.log(e.key, e.oldValue, e.newValue);
});

IndexedDB is a low-level, asynchronous, transactional database built into the browser. Unlike Web Storage, it can store structured objects (not just strings), supports indexes for efficient querying, and handles large datasets (hundreds of MB). It is the recommended storage solution for offline-capable web apps and PWAs that need to persist complex data.

javascript
// Open (or create) a database
const request = indexedDB.open("MyAppDB", 1);

// Create schema on first open / version upgrade
request.onupgradeneeded = function(e) {
  const db = e.target.result;
  const store = db.createObjectStore("products", { keyPath: "id" });
  store.createIndex("by_name", "name", { unique: false });
};

request.onsuccess = function(e) {
  const db = e.target.result;

  // Write a record
  const tx = db.transaction("products", "readwrite");
  tx.objectStore("products").add({ id: 1, name: "Laptop", price: 999 });

  // Read a record
  const getTx = db.transaction("products", "readonly");
  getTx.objectStore("products").get(1).onsuccess = function(e) {
    console.log(e.target.result);   // { id:1, name:"Laptop", price:999 }
  };
};

The HTML5 Application Cache (AppCache) allowed web pages to work offline by declaring a manifest file. It was deprecated due to numerous design flaws — unpredictable update behavior, aggressive caching, and inability to handle dynamic resources. It has been removed from modern browsers. The replacement is the Service Worker API combined with the Cache API, which gives full programmatic control over caching strategies.

javascript
// Modern approach: Service Worker with Cache API
// register in your main JS
if ("serviceWorker" in navigator) {
  navigator.serviceWorker.register("/sw.js").then(reg => {
    console.log("SW registered:", reg.scope);
  });
}

// sw.js — intercept fetch and serve from cache
const CACHE = "v1";
const ASSETS = ["/", "/app.js", "/style.css"];

self.addEventListener("install", e => {
  e.waitUntil(
    caches.open(CACHE).then(cache => cache.addAll(ASSETS))
  );
});

self.addEventListener("fetch", e => {
  e.respondWith(
    caches.match(e.request).then(res => res || fetch(e.request))
  );
});
Web APIs

The Geolocation API provides the user’s geographic coordinates via navigator.geolocation. The browser always asks for permission before sharing location. getCurrentPosition() fetches the position once; watchPosition() continuously tracks movement. It only works on HTTPS (or localhost) in modern browsers.

javascript
if ("geolocation" in navigator) {
  // One-time position fetch
  navigator.geolocation.getCurrentPosition(
    function(position) {
      const { latitude, longitude, accuracy } = position.coords;
      console.log(`Lat: ${latitude}, Lng: ${longitude}`);
      console.log(`Accuracy: ${accuracy} metres`);
    },
    function(error) {
      switch(error.code) {
        case error.PERMISSION_DENIED:   console.log("Denied"); break;
        case error.POSITION_UNAVAILABLE: console.log("Unavailable"); break;
        case error.TIMEOUT:             console.log("Timeout"); break;
      }
    },
    { enableHighAccuracy: true, timeout: 5000, maximumAge: 0 }
  );

  // Continuous tracking
  const watchId = navigator.geolocation.watchPosition(updateMap);
  // Stop tracking:
  navigator.geolocation.clearWatch(watchId);
}

Web Workers run JavaScript on a background thread, separate from the main UI thread. This prevents heavy computations from blocking the browser and freezing the user interface. Workers cannot access the DOM directly — they communicate with the main thread via postMessage(). Ideal for CPU-intensive tasks: data parsing, image processing, cryptography.

javascript
// main.js — create and communicate with the worker
const worker = new Worker("worker.js");

worker.postMessage({ data: [1, 2, 3, 4, 5], op: "sum" });

worker.onmessage = function(e) {
  console.log("Result from worker:", e.data);   // 15
};

worker.onerror = function(e) {
  console.error("Worker error:", e.message);
};

// Terminate when done
worker.terminate();
javascript
// worker.js — runs in background thread
self.onmessage = function(e) {
  const { data, op } = e.data;

  if (op === "sum") {
    const result = data.reduce((a, b) => a + b, 0);
    self.postMessage(result);   // send result back
  }
};

WebSockets establish a persistent, full-duplex communication channel between the browser and server over a single TCP connection. Unlike HTTP (which is request-response), either side can send data at any time with minimal overhead. WebSockets are ideal for real-time applications: chat, live scores, collaborative editing, stock tickers.

javascript
// Create a WebSocket connection
const ws = new WebSocket("wss://chat.example.com/room/1");

// Connection established
ws.addEventListener("open", function() {
  console.log("Connected");
  ws.send(JSON.stringify({ type: "join", user: "Ana" }));
});

// Receive messages
ws.addEventListener("message", function(e) {
  const msg = JSON.parse(e.data);
  displayMessage(msg);
});

// Connection closed
ws.addEventListener("close", function(e) {
  console.log("Disconnected:", e.code, e.reason);
});

// Error handling
ws.addEventListener("error", function(e) {
  console.error("WebSocket error");
});

// Send data at any time
document.getElementById("send-btn").onclick = function() {
  ws.send(JSON.stringify({ type: "message", text: "Hello!" }));
};

// Close the connection
ws.close(1000, "User left");

HTML5 includes a native Drag and Drop API that lets users drag elements to reorder them or drop files from the desktop. Make an element draggable with draggable="true", then handle the dragstart, dragover, and drop events. The dataTransfer object carries data between the drag source and drop target.

html
<div id="drag-me" draggable="true">Drag me!</div>
<div id="drop-zone">Drop here</div>
javascript
const draggable = document.getElementById("drag-me");
const dropZone  = document.getElementById("drop-zone");

draggable.addEventListener("dragstart", function(e) {
  e.dataTransfer.setData("text/plain", this.id);
  e.dataTransfer.effectAllowed = "move";
});

dropZone.addEventListener("dragover", function(e) {
  e.preventDefault();                // allow drop
  e.dataTransfer.dropEffect = "move";
});

dropZone.addEventListener("drop", function(e) {
  e.preventDefault();
  const id = e.dataTransfer.getData("text/plain");
  this.appendChild(document.getElementById(id));
});

// Drop files from the desktop
dropZone.addEventListener("drop", function(e) {
  e.preventDefault();
  const files = e.dataTransfer.files;
  [...files].forEach(file => console.log(file.name, file.size));
});
Accessibility & ARIA

ARIA (Accessible Rich Internet Applications) is a set of HTML attributes that add semantic meaning to elements for assistive technologies when native HTML semantics are insufficient. The golden rule: use native HTML first — a <button> is always better than <div role="button">. ARIA should only be used to bridge gaps where native elements cannot describe the UI pattern.

html
<!-- role: landmark or widget type -->
<div role="alert">Form submitted successfully!</div>
<div role="dialog" aria-modal="true" aria-labelledby="dlg-title">
  <h2 id="dlg-title">Confirm Delete</h2>
</div>

<!-- aria-label: text label for unlabelled elements -->
<button aria-label="Close menu"><i class="bi bi-x"></i></button>

<!-- aria-expanded: toggle state -->
<button aria-expanded="false" aria-controls="menu">Menu</button>
<ul id="menu" hidden>...</ul>

<!-- aria-live: announce dynamic updates -->
<div aria-live="polite" aria-atomic="true">
  Loading results...
</div>

<!-- aria-hidden: hide decorative elements -->
<span aria-hidden="true">★★★★☆</span>
<span class="sr-only">4 out of 5 stars</span>

The alt attribute on <img> serves three purposes: it is read aloud by screen readers for visually impaired users, it is displayed when the image fails to load, and it is indexed by search engines. Rules: describe the content and function of the image concisely; use alt="" (empty) for purely decorative images to tell screen readers to skip them.

html
<!-- Informative image — describe what it shows -->
<img src="chart.png" alt="Bar chart showing 40% increase in revenue Q4 2024">

<!-- Functional image (link/button) — describe its action -->
<a href="/">
  <img src="logo.svg" alt="DevScripts — Home">
</a>

<!-- Decorative — empty alt, screen readers skip it -->
<img src="divider.png" alt="">

<!-- NEVER do this -->
<img src="graph.png" alt="image">       <!-- ⚠️ useless -->
<img src="graph.png">                   <!-- ⚠️ missing alt -->
Meta, Head & Performance

Meta tags provide metadata about the page to browsers, search engines, and social platforms. The essentials are charset, viewport (for responsive design), and description. Open Graph and Twitter Card tags control how the page appears when shared on social media.

html
<head>
  <!-- Character encoding — must be first -->
  <meta charset="UTF-8">

  <!-- Responsive viewport -->
  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <!-- SEO -->
  <meta name="description" content="Learn HTML5 with practical examples.">
  <meta name="keywords" content="HTML5, web development, tutorial">
  <meta name="author" content="Jane Smith">

  <!-- Prevent caching (for dynamic pages) -->
  <meta http-equiv="Cache-Control" content="no-cache">

  <!-- Open Graph (Facebook, LinkedIn) -->
  <meta property="og:title" content="HTML5 Guide">
  <meta property="og:description" content="Everything you need to know.">
  <meta property="og:image" content="https://example.com/preview.jpg">
  <meta property="og:url" content="https://example.com/html5">

  <!-- Twitter Card -->
  <meta name="twitter:card" content="summary_large_image">
  <meta name="twitter:title" content="HTML5 Guide">
</head>

Without attributes, a <script> in <head> blocks HTML parsing while the script downloads and executes. async downloads in parallel but executes as soon as it downloads, potentially out of order. defer downloads in parallel and executes in document order only after HTML parsing is complete. defer is almost always the right choice for application scripts.

html
<!-- Blocks HTML parsing — avoid for large scripts -->
<script src="app.js"></script>

<!-- async: runs as soon as downloaded (no order guarantee) -->
<!-- Use for independent scripts like analytics -->
<script src="analytics.js" async></script>

<!-- defer: runs after HTML parsed, in document order ✓ -->
<!-- Use for all regular application scripts -->
<script src="vendor.js" defer></script>
<script src="app.js"    defer></script>

<!-- Type module scripts are deferred by default -->
<script type="module" src="main.js"></script>

<picture> gives full art-direction control over which image is displayed. With just srcset, the browser chooses the best resolution for the screen density. With <picture>, you can serve entirely different images for different media conditions (different crops for mobile vs. desktop) and different formats (WebP for modern browsers, JPEG as fallback).

html
<!-- srcset only: resolution switching -->
<img src="photo-800.jpg"
     srcset="photo-400.jpg 400w, photo-800.jpg 800w, photo-1200.jpg 1200w"
     sizes="(max-width: 600px) 100vw, 50vw"
     alt="Mountain view">

<!-- <picture>: art direction + format selection -->
<picture>
  <!-- Modern format (WebP) for supporting browsers -->
  <source type="image/webp" srcset="photo.webp">

  <!-- Different crop for mobile -->
  <source media="(max-width: 600px)" srcset="photo-portrait.jpg">

  <!-- Default fallback -->
  <img src="photo-landscape.jpg" alt="Mountain view">
</picture>

href (Hypertext Reference) establishes a link to another resource — it does not embed the resource into the page. Used on <a> and <link>. src (Source) tells the browser to embed and execute/display the referenced resource directly in the document. Used on <script>, <img>, <iframe>, <audio>, and <video>.

html
<!-- href: link — browser navigates TO it -->
<a href="https://example.com">Visit</a>

<!-- href on link: loads stylesheet but doesn't block page -->
<link rel="stylesheet" href="style.css">

<!-- src: embed — browser fetches and renders IT -->
<img src="photo.jpg" alt="Photo">
<script src="app.js"></script>
<iframe src="widget.html"></iframe>
<video src="clip.mp4" controls></video>

<!-- Wrong usage -->
<a src="page.html">Wrong</a>     <!-- ⚠️ -->
<img href="photo.jpg">           <!-- ⚠️ -->
Prev
Next
Drag
Map
HTML Snippets Powered By : XYZScripts.com
Select the fields to be shown. Others will be hidden. Drag and drop to rearrange the order.
  • Image
  • SKU
  • Rating
  • Price
  • Stock
  • Availability
  • Add to cart
  • Description
  • Content
  • Weight
  • Dimensions
  • Additional information
Click outside to hide the comparison bar
Compare