Skip to content

Using SVG icons in CSS can enhance your web design by providing scalable and customizable graphics. Here are several methods to incorporate SVG icons into your CSS:

1. Using SVG as a Background Image

You can use SVG files as background images in your CSS. This method is straightforward and allows you to apply CSS properties like background-size, background-position, and background-repeat.

Example:

css
.icon {
    width: 50px;
    height: 50px;
    background-image: url('icon.svg');
    background-size: contain; /* or cover */
    background-repeat: no-repeat;
}

2. Inline SVG in HTML

You can directly embed SVG code within your HTML. This method allows for greater control over the SVG's styling using CSS.

Example:

html
<svg class="icon" viewBox="0 0 64 64" width="64" height="64">
    <path d="M32 0 L64 64 H0 Z" fill="currentColor"/>
</svg>

CSS:

css
.icon {
    fill: red; /* Change the color of the SVG */
}

3. Using SVG Sprites

SVG sprites allow you to store multiple SVG icons in a single file and reference them using the <use> element. This method reduces HTTP requests and keeps your HTML clean.

Example:

html
<svg style="display: none;">
    <symbol id="icon-home" viewBox="0 0 64 64">
        <path d="M32 0 L64 64 H0 Z"/>
    </symbol>
</svg>

<svg class="icon">
    <use href="#icon-home"></use>
</svg>

CSS:

css
.icon {
    width: 50px;
    height: 50px;
    fill: blue; /* Change the color of the icon */
}

4. Data URI

You can also embed SVG directly in your CSS using a Data URI. This method is useful for small icons.

Example:

css
.icon {
    width: 50px;
    height: 50px;
    background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64"><path d="M32 0 L64 64 H0 Z" fill="green"/></svg>');
    background-size: contain;
    background-repeat: no-repeat;
}

5. CSS Filters

If you need to change the color of an SVG icon that is used as a background image, you can apply CSS filters.

Example:

css
.icon {
    width: 50px;
    height: 50px;
    background-image: url('icon.svg');
    filter: invert(100%) sepia(0%) saturate(0%) hue-rotate(180deg); /* Change color */
}

Conclusion

Using SVG icons in CSS offers flexibility and scalability for web design. Depending on your needs, you can choose from various methods such as background images, inline SVG, SVG sprites, Data URIs, or CSS filters to effectively integrate SVG icons into your projects 12.