CPCODELAB
HTML

Inline SVG Basics

10 min read

Scalable Vector Graphics in HTML

SVG (Scalable Vector Graphics) describes images with XML-like markup. When you place SVG inline in your HTML, you get sharp graphics at any resolution, full CSS control, and the ability to animate or manipulate individual parts with JavaScript.

A Simple Inline SVG

html
<!-- A blue circle with a red stroke -->
<svg
  xmlns="http://www.w3.org/2000/svg"
  width="100"
  height="100"
  viewBox="0 0 100 100"
  aria-label="Blue circle"
  role="img"
>
  <circle cx="50" cy="50" r="40" fill="#3b82f6" stroke="#ef4444" stroke-width="4" />
</svg>

<!-- A simple icon button using SVG -->
<button aria-label="Expand menu">
  <svg
    xmlns="http://www.w3.org/2000/svg"
    width="24"
    height="24"
    viewBox="0 0 24 24"
    aria-hidden="true"
    focusable="false"
  >
    <line x1="3" y1="6" x2="21" y2="6" stroke="currentColor" stroke-width="2" />
    <line x1="3" y1="12" x2="21" y2="12" stroke="currentColor" stroke-width="2" />
    <line x1="3" y1="18" x2="21" y2="18" stroke="currentColor" stroke-width="2" />
  </svg>
</button>

Key SVG Elements and Attributes

  • viewBox="minX minY width height" — Defines the SVG coordinate system. Essential for scaling.
  • <circle cx cy r> — A circle centred at (cx, cy) with radius r.
  • <rect x y width height rx> — A rectangle; rx rounds the corners.
  • <line x1 y1 x2 y2> — A straight line between two points.
  • <path d> — Arbitrary shape using path commands (M, L, C, Z, etc.).
  • fill / stroke — Set colour. Use currentColor to inherit the CSS color property.
  • aria-hidden="true" — Hides decorative SVGs from screen readers.

For icon-only buttons, put aria-hidden="true" on the <svg> and add aria-label to the <button> instead. This gives screen readers a clean label without reading raw SVG markup.

Because inline SVG is just HTML, you can target its elements with CSS (circle { fill: red; }) and attach event listeners with JavaScript. This makes inline SVG the preferred method for interactive icons, charts, and illustrations.

Ready to test yourself?
Practice HTML— quiz & coding exercises