Geekflare is supported by our audience. We may earn affiliate commissions from buying links on this site.
Share on:

How to use SVG in HTML for Designing Stunning Graphics

How-to-use-SVG-in-HTML-for-Designing-Stunning-Graphics
Invicti Web Application Security Scanner – the only solution that delivers automatic verification of vulnerabilities with Proof-Based Scanning™.

If you are a front-end developer, you already understand how getting the right images and blending them with your overall design might be challenging. You may have encountered a poorly-scaled logo or images that look less professional on a web page. 

We also live in a world where we need responsive applications as end users can browse the apps using gadgets with varying screen sizes. As a web developer, you need assurance that the images you add to your website are optimized for different screen sizes, irrespective of whether the users are on smartphones, tablets, or personal computers.  

Scalable Vector Graphics (SVG) file formats solve some of these challenges. This article will define SVG files, how to use them with HTML, and their benefits over other file formats and best practices. 

What are SVG images?

Scalable Vector Graphics, SVG, is an image format that utilizes vector data. SVG files suit non-photographic images on your websites, such as icons and logos. Unlike other images defined using pixels, SVGs are based on vector data. 

There exist different file formats today. However, we have two major categorizations; raster graphics and vector graphics. 

JPEG and PNG files are examples of Raster graphics. These graphics store image information in a bitmap (a grid of colored squares). When the squares in the bitmap are combined, they form an image that acts similarly to a computer screen’s pixels. 

SVG and PDF are examples of vector graphics. These files are written in XML markup language. The XML code in such a file will specify all the text, colors, and shapes that make up the image. 

SVG images have specific-use cases, especially in web development. You can use them in the following instance;

  • Logos: A good website should have a logo that people can resonate with. You can add logos to letters, your company merchandise, website headers, and so much more. Logos saved in SVG formats can suit different use cases without losing their quality. 
  • Icons: Website icons are pictures or symbols that act like links or buttons. Perfect examples are social icons that link to social media pages such as Facebook and Instagram. Such files have clearly defined borders and are also simple. Such icons must be responsive to different screen sizes, necessitating saving them in SVG format. 
  • Animations: Modern websites have images and videos that change their appearance dynamically. You can create animated SVG files to engage users and add visual flair. 
  • Data visualization and Infographics: If you have an informational website, you can save your infographics and charts in SVG format. A perfect example will be a campaign that targets a certain number of people. You can have a chart in SVG format with a progress bar that updates automatically with every sign-up. 
  • Illustrations: If you have decorative drawings you want to add to your web pages, saving them in SVG format ensures that they maintain their quality irrespective of whether they are scaled upwards or downwards. 

How to use SVG in HTML

We use svg element as a container that defines the coordinate system and the viewbox. The svg tag contains the image elements and also defines the frames of this image. 

The viewBox property defines the internal size of an image. On the other hand, we use height and width properties to determine how much space the image will take in the browser. 

If you want to follow along, do the following; 

  • Download the image we will be using from Pixabay for free. (Ensure you select the .svg format). 
  • Create a new project, add an assets folder, and store your downloaded image here. Rename the image as decorative.svg
  • Create index.html and styles.css  files. Link the two files;
<head>

    <link rel="stylesheet" type="text/css" href="styles.css">

</head>

We can now go ahead and demonstrate the different ways to use SVG in HTML:

Method 1: Use svg as an image 

You can enclose your svg image with <img> tag. This is a self-closing tag, so you do not have to open and close it. 

A simple representation of svg as an image will be as follows. 

<img src= "(your image)"  />

You can change your entire HTML as follows;

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta http-equiv="X-UA-Compatible" content="IE=edge">

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

    <title>Document</title>

    <link rel="stylesheet" type="text/css" href="styles.css">

</head>

<body>

    <h2>Use SVG as an image demonstration</h2>

    <img src= "assets/decorative.svg" alt= "svg as an image" />

</body>

</html>

Add simple styling to the styles.css file to define the width and height properties of the svg image. 

img {

    height: 200px;

    width: 300px;

  }

The final output when you run the code on the browser should be as displayed below;

Method 2: Use SVG as a background image 

You can use an svg as a background of a certain section of html page or the entire body. We use CSS to define the background-image property. 

Clear everything on the body section of your html document. 

You can then add this to the styles.css sheet;

body{

    background-image: url(/assets/decorative.svg);

    height: 10px;

    width: 5px;

  }

When you render the code on the browser, you will have something like this;

render the code on the browser

Method 3: Use SVG as an <embed>

You can use the <embed> HTML tag to enclose an SVG image. 

You can define it on your HTML file as follows;

<embed src= “(your image)” />

We can use this code on our index.html file;

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta http-equiv="X-UA-Compatible" content="IE=edge">

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

    <title>Document</title>

    <link rel="stylesheet" type="text/css" href="styles.css">

</head>

<body>

    <h2>How to embed SVG in HTML</h2>

    <embed src="/assets/decorative.svg" />

</body>

</html>

The rendered SVG image will appear as follows;

Using SVG as an embed is recommended as it is not good for search engine optimization. 

Method 4: Use SVG as an inline element

This method allows you to include SVG elements using the <svg>...</svg> tag. 

Do the following;

  • Open the image on your code editor and copy the entire code (it will be more than ten thousand lines). 
  • Create a div and include your code as follows;
<div>

 // Put your SVG code here

</div>

The rendered item will appear as follows;

Using SVG as an inline element is not advisable as it adds a lot of code to your HTML document, affecting the loading speed. 

Method 5: Use SVG as an <iframe>

The <iframe> element is mostly used to embed another HTML webpage/ document within the current webpage/document. 

The general layout for using SVG as in iframe is;

   <iframe src="(you image") </iframe>

You can change your HTML file as follows;

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta http-equiv="X-UA-Compatible" content="IE=edge">

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

    <title>Document</title>

    <link rel="stylesheet" type="text/css" href="styles.css">

</head>

<body>

    <h1>Use SVG with iframe</h1>

    <iframe src="./assets/decorative.svg" width="400px" height="200px"></iframe>

</body>

</html>

The rendered webpage will appear as follows;

image-299

Method 6: Use an SVG as an <object>

The <object> tag in HTML can be used to enclose various content types such as video, audio, and images in various formats such as SVG.

The general format of embedding SVG as an object is as follows;  

<object data="(you SVG image)" type="image/svg+xml"></object>

Add this code to your HTML file;

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta http-equiv="X-UA-Compatible" content="IE=edge">

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

    <title>Document</title>

    <link rel="stylesheet" type="text/css" href="styles.css">

</head>

<body>

    <h2>Use SVG as an Object</h2>

    <object data="./assets/decorative.svg" width="300" height="300"> </object>

</body>

</html>

The rendered webpage will appear as shown below;

rendered webpage

Benefits of using SVG in HTML

  • Scalability: SVG files are resolution-independent, meaning you can scale them to any size without losing their quality. When you extend the dimensions of an SVG file, the browser will automatically recalculate the math behind it to ensure there is no distortion of quality. 
  • Editable: It is easy to redesign your SVG files by changing things such as colors. For instance, you can edit your logo to appear in different shades on different parts of your website. 
  • SEO friendly: SVG files are written in XML, making it easy to include keywords and search phrases in titles and descriptions. 
  • Small file size: SVG images are smaller than PNGs and JPEGs. You can save SVG files in compact sizes but still retain their quality. 

SVG in HTML: Best Practices

  • Optimizing SVG file size: You can minimize the size of the SVG files by removing unnecessary metadata. You can also use the GZIP compression technique to reduce the size of these files. 
  • Cross-Browser Compatibility: Test your SVG files across different screen sizes to ensure they are optimized. 
  • Label SVG files for accessibility and SEO: Use <desc> and <title> tags inside SVG files to make your images discoverable online. 
  • Use an external stylesheet when applicable: If you have multiple SVG files in your web app, you can use an external style sheet as it makes your code easy to maintain and update. You can also use the same styling across different SVG files, reducing time spent writing code. 

Conclusion 

You now have different approaches to using SVG in HTML at your disposal. The choice of approach will depend on what you want to achieve and your preference. For instance, if you want to use SVG as a background image, you have to include it in your CSS file.

However, you can pick either SVG as an image or SVG as an object if you want to add icons or logos to your web application.

You may also explore some top CSS animation libraries for stunning web design projects.

Thanks to our Sponsors
More great readings on Development
Power Your Business
Some of the tools and services to help your business grow.
  • Invicti uses the Proof-Based Scanning™ to automatically verify the identified vulnerabilities and generate actionable results within just hours.
    Try Invicti
  • Web scraping, residential proxy, proxy manager, web unlocker, search engine crawler, and all you need to collect web data.
    Try Brightdata
  • Semrush is an all-in-one digital marketing solution with more than 50 tools in SEO, social media, and content marketing.
    Try Semrush
  • Intruder is an online vulnerability scanner that finds cyber security weaknesses in your infrastructure, to avoid costly data breaches.
    Try Intruder