How to Use Google Material Icons and Symbols on a Website
24/07/2023
CSS Flexbox: A Guide to Flexible Layouts
26/07/2023
This lesson explains how to add an SVG (Scalable Vector Graphics) image to an HTML page and style it with CSS.
1. What is an SVG image?
SVG is an XML-based format for describing two-dimensional vector graphics. Vector shapes can be scaled without losing their sharpness.
A raster image stores a grid of pixels with color information. It works well for photographs and detailed textures, but enlarging an image beyond its resolution can make it look soft or pixelated. JPEG, PNG, and GIF are common raster formats.
2. Image formats and their uses
SVG, PNG, JPEG, GIF, and WebP all have distinct strengths. Choose a format that fits the type of image and how it will be used.
SVG (Scalable Vector Graphics):
- Characteristics: XML-based vector graphics that can scale cleanly.
- Uses: Icons, logos, charts, and illustrations made from vector shapes.
PNG (Portable Network Graphics):
- Characteristics: Raster graphics with lossless compression and support for transparency.
- Uses: Screenshots, graphics with text or hard edges, transparent images, and other images you want to preserve losslessly.
JPEG (Joint Photographic Experts Group):
- Characteristics: Raster graphics with lossy compression to reduce file size.
- Uses: Photographs and images with smooth color gradients. Use another format if you need alpha transparency or crisp, lossless reproduction of fine text and edges.
GIF (Graphics Interchange Format):
- Characteristics: Raster images with a palette of up to 256 colors per frame, support for simple transparency, and animation.
- Uses: Simple animations, such as banners or icons with limited colors. Modern formats may offer smaller files or better color.
WebP:
- Characteristics: A raster format with lossy and lossless compression, transparency, and animation support.
- Uses: Photos and graphics where you want to balance file size and visual quality.
3. Ways to add SVG with HTML and CSS
The examples use the Eniun icon SVG and a simple vector circle.
3.1. Use an <img> element
Set the image’s src to the SVG file. Write useful alternative text in alt if it conveys information. Use an empty alt when it is purely decorative.
<img src="https://www.eniun.com/wp-content/uploads/eniun.svg" alt="Eniun">
Without explicit dimensions, the browser uses the SVG’s intrinsic sizing information and the applicable layout rules. You can also set dimensions using CSS or HTML.
Resize an SVG image with CSS:
Set the width and use height: auto to keep its proportions.
<!-- SVG image with no explicit size --> <img class="svg-img" src="image.svg" alt="Example vector illustration">
img.svg-img {
width: 200px;
height: auto; /* Preserve the aspect ratio */
}
Resize an SVG image in HTML:
Set proportional width and height attributes on the image.
<img src="image.svg" alt="Example vector illustration" width="300" height="200">
3.2. Use inline SVG
Paste the SVG markup directly into the HTML document to make its shapes available to the page’s CSS.
- Open the SVG file in a code editor.
- Copy the complete markup, including the surrounding
<svg>tags. - Paste it into the HTML document where the image belongs, inside
<body>.
<body>
<!-- Insert the SVG markup here -->
<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100" viewBox="0 0 100 100">
<circle cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="red" />
</svg>
</body>
Inline SVG avoids a separate request for that asset. It makes the HTML longer, and a separate file can often be cached across pages.
Inline markup lets page styles target individual shapes and paths.
3.3. Embed an SVG using <object>
An <object> embeds the SVG as a separate document.
Set the object’s dimensions with CSS or HTML attributes. Add meaningful fallback content inside the element.
<object type="image/svg+xml" data="image.svg" width="300" height="200"> The vector illustration could not be displayed. </object>
In this example:
type="image/svg+xml"identifies the media type.data="image.svg"points to the SVG file.width="300"andheight="200"specify the embedding box.
The embedded SVG has its own document and styling. Use inline SVG when the parent page needs to style its internal paths directly.
3.4. Embed an SVG using <iframe>
An iframe also loads the SVG as a separate document. Use it when that separation is useful.
Here is how to load an SVG in an iframe:
<iframe src="image.svg" width="300" height="200" title="Example vector illustration"></iframe>
In this example:
src="image.svg"gives the address of the SVG file.width="300"andheight="200"size the iframe viewport.- The
titledescribes the embedded content.
Things to consider when using an iframe:
Embedding many separate documents adds complexity to a page.
- Maintenance: Each frame has its own document, layout, and loading behavior.
- Search: Keep essential copy in the parent document where it can be read in context. A frame remains a separate resource.
- Sizing: The SVG remains vector artwork. How it fits the frame depends on the SVG’s
viewBox, intrinsic sizing, and the dimensions of the frame.
3.5. Use an SVG as a background image
CSS background-image can apply an SVG behind an HTML element.
In the stylesheet, set the SVG file as the background:
<div class="svg-background">
<!-- Content in the box with the SVG background -->
</div>
.svg-background {
width: 300px;
height: 200px;
background-image: url('image.svg');
background-size: cover;
background-repeat: no-repeat;
}
In this example:
- The class
.svg-backgroundselects the element that carries the image. - The
background-imagedeclaration supplies the SVG file’s URL. background-size: coverscales it to cover the box. It may crop part of the image.background-repeat: no-repeatprevents the image from tiling.
Things to consider when using a background image:
CSS backgrounds work well for decoration that can be omitted without changing the meaning of the page.
- Accessibility: A CSS background has no
altattribute. Use HTML text or an accessible image for meaningful content. - Sizing: The SVG stays sharp as it scales. The box and the background-size settings determine what is visible.
Compare the embedding methods in the demo below:
4. Styling an SVG with CSS
CSS can change an SVG’s color, size, position, or animation. With inline SVG, you can select the shapes inside it.
A complex SVG may contain nested groups and paths. Inspect the markup to see which element receives a style and whether another declaration overrides it.
4.1. Change an SVG’s color
Set fill on an inline SVG shape, or use an inherited value such as currentColor where suitable. An SVG loaded through <img> is a separate image, so page styles cannot select its paths directly.
/* Set the default fill to red */
svg {
fill: red;
}
/* Set a specific shape’s fill by class */
.circle {
fill: blue;
}
4.2. Change an SVG’s size
Use width and height to size the SVG’s box. A suitable viewBox lets the SVG scale its drawing within that box.
/* Set the SVG width to 200px */
svg {
width: 200px;
height: auto; /* Preserve the aspect ratio */
}
Try styling a simple inline SVG in CodePen:
You can also change opacity, positioning, transitions, transforms, filters, and animations.
4.3. Change SVG opacity
Set opacity to control how transparent the entire SVG appears.
/* Make the SVG partially transparent */
svg {
opacity: 0.5;
}
4.4. Change SVG positioning
Use CSS positioning and inset properties such as top and left to move the SVG within the intended containing block.
/* Center the SVG in its containing block */
svg {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
4.5. Animate an SVG with CSS
Use CSS keyframes to animate a shape inside an inline SVG, for example by changing its fill color over time.
/* Define an animation that changes the fill color */
@keyframes changeFill {
0% { fill: red; }
50% { fill: blue; }
100% { fill: green; }
}
/* Apply the animation to the SVG shape */
.circle {
animation: changeFill 2s infinite alternate;
}
Try the different methods with one of your own SVG files. Compare what you can style when you load it as an image and when you inline its markup.