An SVG primer — Scott Murray — alignedleft (2023)

See for the latest, including a new book project. This website is not current and will be retired at some point.

Last updated 2018 December 27

These tutorials address an older version of D3 (3.x) and will no longer be updated. See my book Interactive Data Visualization for the Web, 2nd Ed. to learn all about the current version of D3 (4.x).

D3 is most useful when used to generate and manipulate visuals as SVGs. Drawing with divs and other native HTML elements is possible, but a bit clunky and subject to the usual inconsistencies across different browsers. Using SVG is more reliable, visually consistent, and faster.

Vector drawing software like Illustrator can be used to generate SVG files, but we need to learn how to generate them with code.

The SVG Element

Scalable Vector Graphics is a text-based image format. Each SVG image is defined using markup code similar to HTML. SVG code can be included directly within any HTML document. Every web browser supports SVG except Internet Explorer versions 8 and older. SVG is XML-based, so you’ll notice that elements that don’t have a closing tag must be self-closing. For example:

<element></element> <!-- Uses closing tag --><element/> <!-- Self-closing tag -->

Before you can draw anything, you must create an SVG element. Think of the SVG element as a canvas on which your visuals are rendered. (In that respect, SVG is conceptually similar to HTML’s canvas element.) At a minimum, it’s good to specify width and height values. If you don’t specify these, the SVG will take up as much room as it can within its enclosing element.

<svg width="500" height="50"></svg>

Here is the SVG generated by that code:

Don’t see it? Right-click on the empty space above and choose “Inspect Element”. Your web inspector should look something like this:

(Video) Thoracic Outlet Syndrome: A peripheral nerve surgeon's perspective

An SVG primer — Scott Murray — alignedleft (1)

Note that there is an svg element (yay!), and that it occupies 500 horizontal pixels and 50 vertical pixels. It just doesn’t look like much yet (boo!).

Also note that the browser assumed pixels as the default measurement units. We specified dimensions of 500 and 50, not 500px and 50px. We could have specified px explicitly, or any number of other supported units, including em, pt, in, cm, and mm.

Simple Shapes

There are a number of visual elements that you can include between those svg tags, including rect, circle, ellipse, line, text, and path.

If you’re familiar with computer graphics programming, you’ll recognize the usual pixel-based coordinates system in which 0,0 is the top-left corner of the drawing space. Increasing x values move to the right, while increasing y values move down.

rect draws a rectangle. Use x and y to specify the coordinates of the upper-left corner, and width and height to specify the dimensions. This rectangle fills the entire space of our SVG:

<rect x="0" y="0" width="500" height="50"/>

circle draws a circle. Use cx and cy to specify the coordinates of the center, and r to specify the radius. This circle is centered in the middle of our 500-pixel-wide SVG because its cx (“center-x”) value is 250.

<circle cx="250" cy="25" r="25"/>

ellipse is similar, but expects separate radius values for each axis. Instead of r, use rx and ry.

<ellipse cx="250" cy="25" rx="100" ry="25"/>

line draws a line. Use x1 and y1 to specify the coordinates of one end of the line, and x2 and y2 to specify the coordinates of the other end. A stroke color must be specified for the line to be visible.

<line x1="0" y1="0" x2="500" y2="50" stroke="black"/>

text renders text. Use x to specify the position of the left edge, and y to specify the vertical position of the type’s baseline.

(Video) 05_Eye Believe 2022: D2T1 ”New Advances in Treatment of OM” + ”Understanding Genetics”

<text x="250" y="25">Easy-peasy</text>

text will inherit the CSS-specified font styles of its parent element unless specified otherwise. (More on styling text in a moment.) Notice how the formatting of the sample text above matches that of this paragraph. We could override that formatting as follows:

<text x="250" y="25" font-family="sans-serif" font-size="25" fill="gray">Easy-peasy</text>

Also note that when any visual element runs up against the edge of the SVG, it will be clipped. Be careful when using text so your descenders don’t get cut off (ouch!). You can see this happen when we set the baseline (y) to 50, the same as the height of our SVG:

<text x="250" y="50" font-family="sans-serif" font-size="25" fill="gray">Easy-peasy</text>

path is for drawing anything more complex than the shapes above (like country outlines for geomaps), and will be explained separately. For now, we’ll work with simple shapes.

Styling SVG Elements

SVG’s default style is a black fill with no stroke. If you want anything else, you’ll have to apply styles to your elements. Common SVG properties are:

  • fill — A color value. Just as with CSS, colors can be specified as
    • named colors — orange
    • hex values — #3388aa or #38a
    • RGB values — rgb(10, 150, 20)
    • RGB with alpha transparency — rgba(10, 150, 20, 0.5)
  • stroke — A color value.
  • stroke-width — A numeric measurement (typically in pixels).
  • opacity — A numeric value between 0.0 (completely transparent) and 1.0 (completely opaque).

With text, you can also use these properties, which work just like in CSS:

  • font-family
  • font-size

In another parallel to CSS, there are two ways to apply styles to an SVG element: either directly (inline) as an attribute of the element, or with a CSS style rule.

Here are some style properties applied directly to a circle as attributes:

<circle cx="25" cy="25" r="22" fill="yellow" stroke="orange" stroke-width="5"/>

Alternatively, we could strip the style attributes, assign the circle a class (just as if it were a normal HTML element)

<circle cx="25" cy="25" r="22" class="pumpkin"/>

and then put the fill, stroke, and stroke-width rules into a CSS style that targets the new class:

(Video) Sam Harris: Trump, Religion, Wokeness

.pumpkin { fill: yellow; stroke: orange; stroke-width: 5; }

The CSS approach has a few obvious benefits:

  1. You can specify a style once and have it be applied to multiple elements.
  2. CSS code is generally easier to read than inline attributes.
  3. For those reasons, the CSS approach may be more maintainable and make design changes faster to implement.

Using CSS to apply SVG styles, however, can be disconcerting for some. fill, stroke, and stroke-width, after all, are not CSS properties. (The nearest CSS equivalents are background-color and border.) If it helps you remember which rules in your stylesheet are SVG-specific, consider including svg in those selectors:

svg .pumpkin { /* ... */ }

Layering and Drawing Order

There are no “layers” in SVG, and no real concept of depth. SVG does not support CSS’s z-index property, so shapes can only be arranged within the two-dimensional x/y plane.

And yet, if we draw multiple shapes, they overlap:

<rect x="0" y="0" width="30" height="30" fill="purple"/><rect x="20" y="5" width="30" height="30" fill="blue"/><rect x="40" y="10" width="30" height="30" fill="green"/><rect x="60" y="15" width="30" height="30" fill="yellow"/><rect x="80" y="20" width="30" height="30" fill="red"/>

The order in which elements are coded determines their depth order. The purple square appears first in the code, so it is rendered first. Then, the blue square is rendered “on top” of the purple one, then the green square on top of that, and so on.

Think of SVG shapes as being rendered like paint on a canvas. The pixel-paint that is applied later obscures any earlier paint, and thus appears to be “in front.”

This aspect of drawing order becomes important when you have some visual elements that should not be obscured by others. For example, you may have axes or value labels that appear on a scatterplot. The axes and labels should be added to the SVG last, so they appear in front of any other elements.


Transparency can be useful when elements in your visualization overlap but must remain visible, or you want to de-emphasize some elements while highlighting others.

There are two ways to apply transparency: use an RGB color with alpha, or set an opacity value.

(Video) 5 Periodic Tables We Don't Use (And One We Do)

You can use rgba() anywhere you specify a color, such as with fill or stroke. rgba() expects three values between 0 and 255 for red, green, and blue, plus an alpha (transparency) value between 0.0 and 1.0.

<circle cx="25" cy="25" r="20" fill="rgba(128, 0, 128, 1.0)"/><circle cx="50" cy="25" r="20" fill="rgba(0, 0, 255, 0.75)"/><circle cx="75" cy="25" r="20" fill="rgba(0, 255, 0, 0.5)"/><circle cx="100" cy="25" r="20" fill="rgba(255, 255, 0, 0.25)"/><circle cx="125" cy="25" r="20" fill="rgba(255, 0, 0, 0.1)"/>

Note that with rgba(), transparency is applied to the fill and stroke colors independently. The following circles’ fill is 75% opaque, while their strokes are only 25% opaque.

<circle cx="25" cy="25" r="20" fill="rgba(128, 0, 128, 0.75)" stroke="rgba(0, 255, 0, 0.25)" stroke-width="10"/><circle cx="75" cy="25" r="20" fill="rgba(0, 255, 0, 0.75)" stroke="rgba(0, 0, 255, 0.25)" stroke-width="10"/><circle cx="125" cy="25" r="20" fill="rgba(255, 255, 0, 0.75)" stroke="rgba(255, 0, 0, 0.25)" stroke-width="10"/>

To apply transparency to an entire element, set an opacity attribute. Here are some completely opaque circles

followed by the same circles, with opacity values:

<circle cx="25" cy="25" r="20" fill="purple" stroke="green" stroke-width="10" opacity="0.9"/><circle cx="65" cy="25" r="20" fill="green" stroke="blue" stroke-width="10" opacity="0.5"/><circle cx="105" cy="25" r="20" fill="yellow" stroke="red" stroke-width="10" opacity="0.1"/>

You can employ opacity on an element that also has colors set with rgba(). When doing so, the transparencies are multiplied. The following circles use the same RGBA values for fill and stroke. The first circle below has no element opacity set, but the other two do:

<circle cx="25" cy="25" r="20" fill="rgba(128, 0, 128, 0.75)" stroke="rgba(0, 255, 0, 0.25)" stroke-width="10"/><circle cx="65" cy="25" r="20" fill="rgba(128, 0, 128, 0.75)" stroke="rgba(0, 255, 0, 0.25)" stroke-width="10" opacity="0.5"/><circle cx="105" cy="25" r="20" fill="rgba(128, 0, 128, 0.75)" stroke="rgba(0, 255, 0, 0.25)" stroke-width="10" opacity="0.2"/>

Notice how the third circle’s opacity is 0.2 or 20%. Yet its purple fill already has an alpha value of 0.75 or 75%. The purple area, then, has a final transparency of 0.2 times 0.75 = 0.15 or 15%.

For more on SVG — including patterns, animation, paths, clip-paths, masks, and filters — see the “Pocket Guide to Writing SVG” by Joni Trythall as well as “An SVG Primer for Today’s Browsers” by David Dailey.

Next up: Drawing SVGs

These tutorials address an older version of D3 (3.x). See my book Interactive Data Visualization for the Web, 2nd Ed. to learn all about the current version of D3 (4.x).

Download the sample code files and sign up to receive updates by email. Follow me on Twitter for other updates.

These tutorials have been generously translated to Catalan (Català) by Joan Prim, Chinese (简体中文) by Wentao Wang, French (Français) by Sylvain Kieffer, Japanese (日本語版) by Hideharu Sakai, Russian (русский) by Sergey Ivanov, and Spanish (Español) by Gabriel Coch.

(Video) This dog was dumped in a park and left to starve...


Does SVG need a closing tag? ›

No. It does not have an end tag. Example. <circle cx="50" cy="50" r="40" /> All SVG elements dont have an end tag.

Does an SVG have layers? ›

There are no “layers” in SVG, and no real concept of depth. SVG does not support CSS's z-index property, so shapes can only be arranged within the two-dimensional x/y plane. The order in which elements are coded determines their depth order. The purple square appears first in the code, so it is rendered first.

How to use SVG tag in HTML? ›

An SVG image begins with an <svg> element. The width and height attributes of the <svg> element define the width and height of the SVG image. The <circle> element is used to draw a circle. The cx and cy attributes define the x and y coordinates of the center of the circle.

What is an SVG viewBox? ›

The viewBox attribute defines the position and dimension, in user space, of an SVG viewport. The value of the viewBox attribute is a list of four numbers: min-x , min-y , width and height .

Should I wrap SVG in a span? ›

It is in my opinion, that you should be wrapping them in a span element. This is because span is more semantically correct. This is the following from W3: The tag defines a division or a section in an HTML document.

When should you not use SVG? ›

Because SVG is vector-based, it does not work well for images with lots of fine details and textures like photographs. SVG is best suited for logos, icons, and other “flat” graphics that use simpler colors and shapes. Also, while most modern browsers support SVG, older browsers may not work with them properly.

What are the disadvantages of SVG? ›

The disadvantages of SVG images
  • Cannot support as much detail. Since SVGs are based on points and paths instead of pixels, they can't display as much detail as standard image formats. ...
  • SVG doesn't work on legacy browsers. Legacy browsers, such as IE8 and lower, don't support SVG.
6 Jan 2016

What are the pros and cons of SVG? ›

it's possible to view the contents of the SVG file in any browser (IE, Chrome, Opera, FireFox, Safari, etc.). Cons: – the file size is growing very fast, if the object consists of a large number of small elements; – it's impossible to read a part of the graphic object, only the entire object and it slows you down.

Is SVG high or low quality? ›

SVG is ideal for high quality images and can be scaled to ANY size. Many people choose file formats based on file size restrictions - adding pictures to your website that will load as quickly as possible to improve SEO, for example.

What SVG stands for? ›

Scalable Vector Graphics (SVG) is a web-friendly vector file format. As opposed to pixel-based raster files like JPEGs, vector files store images via mathematical formulas based on points and lines on a grid.

How do I create an SVG image? ›

How to create and edit an SVG file.
  1. Once you've put together an image in Photoshop, click File > Export > Export As.
  2. Click the Format drop-down menu within the box that appears and then select SVG.
  3. Select Export All and save the file.

What is SVG used for? ›

SVG is short for “Scalable Vector Graphics”. It's a XML based two-dimensional graphic file format. SVG format was developed as an open standard format by World Wide Web Consortium (W3C). The primary use of SVG files are for sharing graphics contents on the Internet.

Do you need viewBox for SVG? ›

viewbox is like a second set of virtual coordinates – all vectors inside the SVG will use the viewbox, while you can manipulate the actual height, width properties of the SVG without affecting the inside,. An SVG with a viewBox is so much easier to work with. I would never put an SVG together without one.

Why use SVG viewBox? ›

The viewBox is an attribute of the SVG element in HTML. It is used to scale the SVG element that means we can set the coordinates as well as width and height. Attribute Values: min-x: It is used to set the horizontal axis.

How to set SVG width and height? ›

Just set the viewBox on your <svg> , and set one of height or width to auto . The browser will adjust it so that the overall aspect ratio matches the viewBox .

How do I make SVG not blurry? ›

How do I Make Sure my Logo is not Blurry, on all Screens?
  1. Uploading a version of your logo that has 2x the required pixel dimensions.
  2. Uploading an SVG version of your image, instead of the typical PNG format.
  3. Installing additional plugins, or software, to provide this functionality.
12 Jun 2021

Do SVG files sell well? ›

CAN YOU MAKE MONEY SELLING SVG FILES? Yes! An average SVG file sells between $1 and $5 per file. Consider creating a lot of files and listing them as bundles too.

Does SVG affect performance? ›

It won't be a problem for your website's performance, but it can negatively impact on your time and your server's bandwidth.

Is SVG still used 2022? ›

Still using PNG for logos and icons? It's time to learn about SVG. It's taken a while, but SVG is now widely supported across all major browsers and devices. SVG files are super-small, searchable, modifiable – via code – and scalable.

What is the best way to use SVG? ›

SVG images can be written directly into the HTML document using the <svg> </svg> tag. To do this, open the SVG image in VS code or your preferred IDE, copy the code, and paste it inside the <body> element in your HTML document. If you did everything correctly, your webpage should look exactly like the demo below.

Why are SVGs so popular? ›

SVGs are scalable and will render pixel-perfect at any resolution whereas JPEGs, PNGs and GIFs will not. SVGs are vector images and therefore are usually much smaller in file-size than bitmap-based images.

What is the main competitor to SVG? ›

js, Raphael, Modernizr, Modernizr, and Lodash are the most popular alternatives and competitors to SVG.

What is special about SVG? ›

SVG stands for scalable vector graphics, and it is a file format that allows you to display vector images on your website. This means that you can scale an SVG image up and down as needed without losing any quality, making it a great choice for responsive web design.

Why are SVGs better? ›

SVGs offer lossless compression — which means they're compressible to smaller file sizes at no cost to their definition, detail, or quality. PNGs also benefit from lossless compression of 5-20%, which can help make up for their large file size.

Is SVG still used? ›

SVG stands for Scalable Vector Graphics, and it's the most widely used vector file format on the web. Let's break this down: Scalable: SVGs can be resized up or down without damaging the quality of the image. It will be perfectly crisp and clear, no matter how large or small it is.

Which is better canvas or SVG? ›

SVG gives better performance with smaller number of objects or larger surface. Canvas gives better performance with smaller surface or larger number of objects. SVG is vector based and composed of shapes. Canvas is raster based and composed of pixel.

How do I use SVG safely? ›

There are several plugins in the WordPress directory that allow you to safely use SVG files on your site.
In addition, there is a premium version, which lets you restrict access who can upload them to your site.
  1. Prepare Your File. ...
  2. Install the Plugin. ...
  3. Upload Your SVG File. ...
  4. Use It on Your Site.
21 Sept 2020

Can SVG be blurry? ›

If an SVG image has been imported into the document, and then scaled up, it appears perfectly fine on-screen, and when exported as a PDF. When it's printed, it appears blurred and pixelated. It looks like the bottom image has been rasterized at 30 x 30 pixels.

Does size matter in SVG? ›

Sizing on SVG is pretty arbitrary as it is a vector format, the layout is done with maths and so isn't dependent on the size you specify. However, if the SVG is rendered on the page and then gets resized size it can make a difference at the rendering stage.

What resolution is SVG? ›


The other key benefit is that SVG is resolution independent, meaning that it will appear exactly the same in a design that is 72 DPI as it would in a 300 DPI alternative. As a result, SVG can be used in both print and web media.

Is SVG good for printing? ›

SVGs are specifically designed for web use, so they aren't usually ideal for large-scale printing. They work best at the size of a computer screen. So, when it comes to detailed charts, tables, or infographics that might require users to zoom in, they're the perfect choice.

What software to use for SVG files? ›

Inkscape. One of the most important tools for a graphics format is a decent drawing program. Inkscape offers state-of-the-art vector drawing, and it's open source. Moreover, it uses SVG as its native file format.

What software do you need to make SVG? ›

Creating SVG files in Adobe Illustrator. Perhaps the easiest way to create sophisticated SVG files is to use a tool that you are likely already familiar with: Adobe Illustrator. While it's been possible to make SVG files in Illustrator for quite some time, Illustrator CC 2015 added and streamlined the SVG features.

What program can I use to design SVG files? ›

Probably the most well-known software for making SVG files is Adobe Illustrator. The function to make SVG files out of bitmap images is “Image Trace”. You can access the tool panel by going to Window > Image Trace.

What decimal should I use for SVG? ›

3) Decimal precision: which one is best? When you save an SVG, you'll need to indicate a decimal precision—usually an integer between one and eight. It defines the number of digits after the decimal point for all numeric values. Remember, characters equal bytes and the less we have, the smaller the file will be.

Can you lazy load SVG? ›

Lazy-Loading to the Rescue

One of the primary benefits of embedding SVG code into an HTML document is that once there, they're part of the DOM, allowing them to be styled, animated, copied, moved, etc., just like any other element on the page.

Do clipping masks work with SVG? ›

Clipping and masking is a feature of SVG that has the ability to fully or partially hide portions of an object through the use of simple or complex shapes.

How to make SVG image responsive? ›

Try adding a container element with a defined width around your SVG, then removing width and height. It should fill the space. You also need to increase the width of the viewBox to accommodate the whole shape. Save this answer.

How do you position SVG elements? ›

When it comes to the positioning of SVG elements like “<rect>” or “<circle>”, there's already a big difference to HTML regarding the syntax. While HTML elements are placed via CSS attributes “left” and “top”, SVG elements can only be placed via “x” and “y” attributes (“cx” and “cy” attributes for circles).

How do I set my viewBox to 100%? ›

Long story short, just use viewBox="0 0 100 100" and you can use numbers between 0 and 100.

How do I scale SVG for printing? ›

To print a 1:1 scale copy of your room, you would need to scale (multiply) your SVG by 1 / worldToPrinterScaleFactor . To print a half-scale copy of your room, you would need to scale (multiply) your SVG by 0.5 / worldToPrinterScaleFactor .

What size should SVG be for Cricut? ›

Cricut Design Space automatically resizes all uploaded SVG files that are over 23.5″ down to a maximum of 23.5″, which can create problems if your project is larger.

Do you need a closing script tag? ›

That's because SCRIPT TAG is not a VOID ELEMENT. In an HTML Document - VOID ELEMENTS do not need a "closing tag" at all! In xhtml, everything is Generic, therefore they all need termination e.g. a "closing tag"; Including br, a simple line-break, as <br></br> or its shorthand <br /> .

Which does not require closing tag? ›

The <hr> tag is an empty tag that does not require a closing tag.

What tags require no closing tag? ›

The void elements or singleton tags in HTML don't require a closing tag to be valid. These elements are usually ones that either stand alone on the page ​or where the end of their contents is obvious from the context of the page itself.

What elements do not require closing tags? ›

End tags on void elements

These elements are called empty or void and only have a start tag since they can't have any content. They must not have an end tag in HTML. The void elements in HTML 4.01/XHTML 1.0 Strict are area , base , br , col , hr , img , input , link , meta , and param .

What happens if you don't close tags? ›

If you don't add a closing tag the browser won't know where it ends. It will take the next tag and think it belongs to the previous tag without the closing tag.

Should I put script tags in head or body? ›

If your is not placed inside a function, or if your script writes page content, it should be placed in the body section. It is a good idea to place scripts at the bottom of the <body> element. This can improve page load, because script compilation can slow down the display.

Where is the best place to put a script tag? ›

The <script> tag can be placed in the <head> section of your HTML or in the <body> section, depending on when you want the JavaScript to load. Generally, JavaScript code can go inside of the document <head> section in order to keep them contained and out of the main content of your HTML document.

What is the difference between an opening tag and a closing tag? ›

An opening tag begins a section of page content, and a closing tag ends it. For example, to markup a section of text as a paragraph, you would open the paragraph with an opening paragraph tag <p> and close it with a closing paragraph tag </p> (closing tags always proceed the element with a /).

Is HR a self-closing tag? ›

The <hr> tag in HTML is used for separating the individual sections of a webpage from each other by adding a horizontal line between them. More precisely, it is used for adding a thematic break between the contents of a webpage. It is a self-closing tag in HTML.

Why is it important to close tags? ›

Closing tags are EXTREMELY important because otherwise it will think all your other tags are part of the element.

What are the 2 basic types of tags? ›

There are two kinds of HTML tags: paired and unpaired. Paired tags require an opening tag that turns a formatting feature on and a closing tag that turns the feature off.

Does closing order tags matter? ›

No, the order you add the tags doesn't matter because you don't actually get to set the order of the tags. Tag order is determined by the popularity of that tag, not by the order you select it.

Does Title tag need to be closed? ›

Both opening and closing tags are required. Note that leaving off </title> should cause the browser to ignore the rest of the page. A <head> element that contains no other <title> element.

What is a self closing tag? ›

Some HTML tags (like img and br ) don't have their own content. These are known as self closing tags or empty tags. They look like this: A simple example: <br /> The br tag inserts a line break (not a paragraph break).

What is difference between tag and element? ›

Tags are used to mark up the start of an HTML element and they are usually enclosed in angle brackets. An example of a tag is: <h1>.
HTML TagsHTML ElementsHTML Attributes
HTML tag starts with < and ends with >Whatever written within a HTML tag are HTML elements.HTML attributes are found only in the starting tag.
2 more rows
11 Jun 2021


1. Operation: Outer Space by Murray Leinster, read by Mark Nelson, complete unabridged audiobook
2. ZAYN, Taylor Swift - I Don’t Wanna Live Forever (Fifty Shades Darker)
(Taylor Swift)
3. The Unstoppable Power of Letting Go | Jill Sherer Murray | TEDxWilmingtonWomen
(TEDx Talks)
4. d3 talk in the Twin Cities
(Ian Johnson)
5. Grading Every Round 1 Pick From The 2022 NFL Draft
(Bleacher Report)
6. Create a Design System with Figma - Full Course
Top Articles
Latest Posts
Article information

Author: Duane Harber

Last Updated: 01/04/2023

Views: 5575

Rating: 4 / 5 (51 voted)

Reviews: 90% of readers found this page helpful

Author information

Name: Duane Harber

Birthday: 1999-10-17

Address: Apt. 404 9899 Magnolia Roads, Port Royceville, ID 78186

Phone: +186911129794335

Job: Human Hospitality Planner

Hobby: Listening to music, Orienteering, Knapping, Dance, Mountain biking, Fishing, Pottery

Introduction: My name is Duane Harber, I am a modern, clever, handsome, fair, agreeable, inexpensive, beautiful person who loves writing and wants to share my knowledge and understanding with you.