A Complete Guide to SVG in CSS

SVG (Scalable Vector Graphics) is a powerful and flexible format for creating vector graphics. In this guide, we’ll explore how to use SVGs in CSS to create dynamic and responsive designs.

Embedding SVG in HTML

Before we can use SVG in CSS, we need to embed the SVG code in our HTML document. We can do this in a few different ways:

Inline SVG

We can include the SVG code directly in our HTML document using the <svg> element:

html
<svg viewBox="0 0 100 100">
<rect x="10" y="10" width="80" height="80" />
</svg>

In this example, we define an SVG element with a viewBox attribute that sets the dimensions of the SVG canvas. We then include a rectangle element inside the SVG element.

External SVG

We can also include SVG code in an external file and reference it in our HTML document using the <object> or <img> elements:

html
<object type="image/svg+xml" data="image.svg"></object>

<img src="image.svg" alt="SVG Image" />

In the first example, we use the <object> element with a type attribute set to image/svg+xml, and a data attribute pointing to the external SVG file. In the second example, we use the <img> element with a src attribute pointing to the external SVG file.

Using SVG in CSS

Once we have embedded our SVG code in our HTML document, we can use it in our CSS to create dynamic and responsive designs. Here are some examples:

Background Image

We can use an SVG as a background image for an element:

css
div {
background-image: url(image.svg);
background-repeat: no-repeat;
background-position: center;
}

In this example, we set the background-image property to the URL of the SVG file, and use the background-repeat and background-position properties to control how the SVG is displayed.

Masking

We can use SVGs to create masks for elements:

css
div {
mask-image: url(mask.svg#mask);
}

In this example, we use the mask-image property to set the mask for the element. The #mask value refers to the id attribute of the SVG element that defines the mask.

Clipping

We can use SVGs to clip elements:

css
div {
clip-path: url(clip.svg#clip);
}

In this example, we use the clip-path property to set the clip for the element. The #clip value refers to the id attribute of the SVG element that defines the clip.

Conclusion

Using SVG in CSS can add a lot of flexibility and power to our designs. By embedding SVG in our HTML and using it in our CSS, we can create dynamic and responsive layouts that would be difficult or impossible to achieve with other formats.