SVG Tag in HTML

Learn via video course
FREE
View all courses
JavaScript Course With Certification: Unlocking the Power of JavaScript
JavaScript Course With Certification: Unlocking the Power of JavaScript
by Mrinal Bhattacharya
1000
4.8
Start Learning
JavaScript Course With Certification: Unlocking the Power of JavaScript
JavaScript Course With Certification: Unlocking the Power of JavaScript
by Mrinal Bhattacharya
1000
4.8
Start Learning
Topics Covered

Overview

SVG is a markup language and a collection of associated graphics script interfaces for defining vector-based graphics for the web. This article discusses the SVG tag in HTML, including how to implement it, how to use it, and how to deal with its accessibility issues. For a better understanding of tags in HTML, visit HTML Tags.

It’s essentially a structured Extensible Markup Language (XML) image format for making web-scale images.

Unlike the pixel-based image formats, SVG is a vector-based graphics format, meaning it can scale up or down to any dimension without loss of quality.

They can be resized to accommodate different display densities, print more clearly, and have improved responsiveness. In SVG files, every element and attribute can be animated. Despite being a vector format, SVGs may be utilized in the same way like their raster counterparts.

IMAGE USING VECTOR GRAPHIC TOOL

This image was created using a vector graphic tool. Because it is an SVG image, it can be resized and altered to meet the requirements of the user.

SVG Tag in HTML

SVG is a container, renderable, structural element in HTML that establishes a new coordinate system and viewport on a webpage. It is used as the page's outermost element, but it may also be used to embed an SVG fragment into another SVG or HTML document. HTML SVG is a modularized language that is used to describe graphics in XML. It describes two-dimensional vector and mixed vector/raster graphics in XML.

The <svg> tag comes in pairs. The content is written between the opening (<svg>) and the closing (</svg>) tags.

Syntax:

<svg></svg>

Attributes

SVG elements can be customized using attributes that indicate how the element should be interpreted and rendered.

The content model of the SVG element is used to define SVG attributes. It contains various elements including animation elements, descriptive elements, paint server elements, shape elements, structural elements, anchor, clipPath, filter, foreignObject, image, marker, mask, script, style, switch, text, and view.

SVG tag supports all core, global, and event attributes, as well as various presentation attributes for styling with CSS.

There are some specific attributes used in the SVG tag. These are:

  • baseProfile The minimum SVG language profile that the document requires. The document's required minimum SVG language profile. It has a string value type and is not animatable. After SVG2, this property is deprecated in usage.

  • contentScriptType For the provided document fragment, it determines the default scripting language. After SVG2, this property is no longer supported.

  • contentStyleType The contentStyleType property on the <svg> element defines the style sheet language for the given document fragment. Because CSS is a widely used style sheet language, this feature is no longer supported after SVG2.

  • preserveAspectRatio The preserveAspectRatio attribute specifies how an element with a certain aspect ratio viewBox must fit into a viewport with a different aspect ratio.

Because the aspect ratio of an SVG image is defined by the viewBox attribute, if this attribute isn't set, the preserveAspectRatio attribute has no effect. It is an animatable attribute. It takes xMidYMid meet as the default value.

Syntax:

HTML

CSS

Output

PRESERVE ASPECT RATIO

For better view checkout here

  • version Defines the version of SVG used for the inner content of the element. After SVG2, it is no longer supported. Its value is a number, and it is not animateable.

  • viewBox An SVG viewport's position and dimension in user space are defined by the viewBox property. The viewBox property takes a list of four values as its value: min-x, min-y, width, and height. The numbers, which are separated by whitespace and/or a comma, define a user-space rectangle that is mapped to the viewport bounds for the corresponding SVG element (not the browser viewport).

Note: The exact effect of this attribute is influenced by the preserveAspectRatio attribute.

  • height The height attribute defines the vertical length of an element in the user coordinate system.

  • width The width attribute defines the horizontal length of an element in the user coordinate system.

  • x The x attribute defines an x-axis coordinate in the user coordinate system.

  • y The y attribute defines a y-axis coordinate in the user coordinate system.

Note: Starting with SVG2, the attributes x, y, width, and height are Geometry Attributes, which means they may be used as CSS properties as well.


How to Use SVG Tag in HTML?

SVG images and their behaviors are defined in XML files. SVGs may be created and modified with a text editor being XML files, although they are usually created with drawing tools like Inkspace.

These are typically used for vector diagrams such as pie charts, 2-Dimensional graphs in an X, Y coordinate system, and so on.

The root of an SVG fragment is specified by the <svg> tag. In SVG files, every element and property may be animated.

SVG allows for three types of graphic objects-

  1. Vector graphic shapes (e.g., paths consisting of shapes and lines)
  2. Images
  3. Text.

The feature set includes nested transformations, clipping paths, alpha masks, filter effects, and template objects.


Different ways to use SVG in HTML


  1. Using SVG as an <img>


    This method is the simplest way to add SVG images to a webpage. Provide the link to the SVG image in the src attribute.

USING IMG

SVG images when added to a page with the <img> element, do not have a size specified. So they retain their original SVG dimensions. The image's height and width can be adjusted to achieve required dimensions.

Note: It is important to keep in mind that while SVG pictures may be resized, there are still limitations on making major style changes to the SVG image.


  1. Using SVG as an <iframe>


    An <iframe> tag can also be used to embed an SVG image, however this is not recommended owing to contemporary browser security constraints.

USING IFRAME


  1. Using SVG as an <object>


    HTML <object> tag can be used to add SVG images to the webpage.

USING OBJECT

  1. Using SVG as an <embed>


    The <embed> element is another way to use an SVG image in HTML.

USING EMBED

Note: Browser plug-ins have been deprecated and deleted in most contemporary browsers. This implies that depending on <embed> to make a site accessible to the ordinary user's browser is generally not a good idea.


  1. Using inline SVG images


    Using the <svg> /svg> element, SVG graphics can be written directly into an HTML text.

    To do so, open the SVG picture in your preferred IDE, copy the code, and paste it into your HTML document's <body> element.

    This involves interleaving HTML and SVG tags in the same HTML document. All of the modern browsers except Internet Explorer treat HTML as though it is XHTML, a dialect of XML, with less stringent syntax constraints. As a result, inlining SVG becomes as simple as resolving various namespaces. In such browsers, HTML and SVG should get along seamlessly.

    SVG inline decreases load time by acting as an HTTP request when used in an HTML page. When compared to either the <img> or css-background-image techniques, this method allows a user with greater customization of SVG graphics.

Output

USING INLINE IMAGE

For more checkout here

Creating Different Shapes Using SVG

The majority of SVG graphics employ a few basic shapes. To create a shape, you insert an element in the <svg> element. Different elements correlate to different forms, and the size and position of those shapes are described using different parameters.

In SVG, the drawn shape is remembered as an object.

These shapes improve the readability of the svg file.

These shape elements don’t have an end tag.

1. SVG Line

The <line> element takes two parameters: the locations of two points and creates a straight line between them. A polyline is a collection of linked straight lines that may be drawn using SVG. Because the list of points might get fairly large, they are all combined into one attribute.

SVG LINE


2. SVG Circle

The <circle> element is used to create a circle. It takes the x and y coordinates of the center of the circle and the circle’s radius as parameters.

SVG CIRCLE IMAGE


3. SVG Rectangle

The <rect> element is used to create a rectangle on the webpage. There are 6 basic attributes that control the position and shape of the rectangles on the screen.

SVG RECTANGLE IMAGE


4. SVG Rounded Rectangle

Setting the rx (the x radius of the rectangle's corners) and ry (the y radius of the rectangle's corners) parameters in a rect element gives it rounded corners. They default to 0 if they aren't set.


SVG ROUNDED CIRCLE IMAGE

5. SVG Star

Using the <polygon> element, SVG components may be utilised to build multiedge shapes. A polygon is similar to a polyline, which is made up of straight line segments that link several locations. In polygons, the path joins the last and initial points automatically, forming a closed shape.

To create a star, set the x and y coordinates of each vertex properly.

SVG STAR SIGN


6. SVG Logo

A logo can be created in SVG using a linear gradient. A linear gradient is defined by the <linearGradient> element. The <linearGradient> element must be nested within the <defs> tag. The <defs> tag is short form for definitions and contains the definition of special elements (such as gradients).

There are 3 types of linear gradients: horizontal, vertical, and angular.

SVG LOGO IMAGE


Why SVG is Preferred over Other Image Formats?

Advantages of using SVG over other image formats (like JPEG and GIF) are:

1. Compatibility with other languages

SVG leverages and integrates with W3C specifications and standards efforts, as described in the following:

  • SVG can be integrated with HTML either by using SVG in HTML or by using HTML in SVG, in both cases either by inclusion or reference.
  • SVG content is styled with CSS.
  • SVG extends DOM4 and offers a comprehensive Document Object Model (DOM).
  • The SVG DOM is quite similar to the HTML DOM in terms of compatibility and consistency.
  • In addition, the SVG DOM supports and includes many of the CSS object model and event handling features.

2. Easily editable

Any text editor can be used to generate and edit SVG images. SVGs can be styled and animated using advancements in CSS and JavaScript functionalities.

EASILY EDITABLE


3. Browser Support

SVGs are becoming more widely supported in browsers, which implies greater quality pictures.


4. Scalability

SVG images are highly scalable that's why they never lose quality no matter how much they are zoomed out or resized. SVG images can be printed with high quality at any resolution.

SCALABILITY

5. Reduced file size

When properly optimized, SVG files can be smaller than other file types. SVGs, unlike raster graphics, do not need to be generated at larger sizes to compensate for higher resolution displays. Using SVG files on your website will allow images to load faster since the file sizes are smaller.

REDUCED FILE SIZE IMAGE

6. Indexable

Because SVG is built on XML, search engines can index and search SVG images, and they can also be programmed and compressed.

As a result, SVG pictures are beneficial for SEO (Search Engine Optimization).


Accessibility Concerns

SVGs are not resolution-dependent and may be resized without degradation because they are vector-based and XML-structured images. With CSS and/or JavaScript, SVGs may be readily edited and animated.

As a result, SVG is ideal for responsive design and reduces page load time (as opposed to using JPG, JPEG, PNG, etc.). While some IE browsers and native Android/Windows phone browsers do not yet support SVG, there are signs that it will soon.

To make inline SVG easily accessible, there are a few best practises that should be observed while utilizing it.

  • Include a <title> tag just below the svg tag in the output XML for SVG.
  • The <title> tag for an SVG, like the alt attribute for an image, should be brief.
  • Include an aria-labelledby attribute in the SVG tag that refers to the <title> tag.
  • If there are many shapes, it's a good idea to provide a title tag for each shape group.
  • Including a <desc> tag (description) in addition to a title tag is quite beneficial to assistive technology users.

While using embedded SVG pictures on your website, make the outer <svg> element role="img" and give it a label. This causes screen readers to see it as a single object and describe it using the label, rather than reading out all of the child nodes:


Browser Compatibility

The SVG tag is supported by various browsers:

  • Google Chrome 4.0 and above
  • Edge 9.0 and above
  • Firefox 3.0 and above
  • Internet Explorer 9.0
  • Opera 10.5 and above
  • Safari 3.2 and above

Note: SVGs are compatible with cross-browsers and gives better consistency and higher fidelity of images.


Conclusion

  • SVG is a vector-based graphics format image and its behavior is defined in XML text files.
  • The HTML <svg> element specifies the root of an SVG fragment. Every element and every attribute in SVG files can be animated.
  • SVG pictures are a great tool for responsive design since they can be scaled to any size without losing quality.
  • SVG is a container element that may hold both graphic and non-graphic components as child elements.
  • Due to their scalability, cross-browser compatibility, and indexability, SVGs are preferred over other image formats.
  • SVG elements can be designed beautifully using the presentation attributes or CSS.

Learn More:

Click here to find detailed information about the SVG element.


tags: <img> <a> <g> <desc> <iframe> <embed> <object>

:::