Craig explains how to add CSS styles to SVGs when used as static images, inlined backgrounds and HTML, sprites, HTML content effects and portable files.
SVG is a lightweight vector image format that’s used to display a variety of graphics on the Web and other environments with support for interactivity and animation. In this article, we’ll explore the various ways to use CSS with SVG, and ways to include SVGs in a web page and manipulate them.
The Scalable Vector Graphic (SVG) format has been an open standard since 1999, but browser usage became practical in 2011 following the release of Internet Explorer 9. Today, SVG is well supported across all browsers, although more advanced features can vary.
Bitmap image formats such as WebP, PNG, JPG, and GIF define the color of individual pixels. A 100
× 100
PNG image requires 10,000 pixels. Each pixel requires four bytes for red, green, blue and transparency, so the resulting file is 40,000 bytes (plus a little more for metadata). Compression is applied to reduce the file size: PNG and GIF use ZIP-like lossless compression, while JPG is lossy and removes less noticeable details (WebP can use either method).
Bitmaps are ideal for photographs and more complex images, but definition is lost as images are enlarged.
SVGs are vector images defined in XML. Points, lines, curves, paths, ellipses, rectangles, text, etc. are drawn on an SVG canvas. For example:
<svg xmlns="https://www.w3.org/2000/svg" viewBox="0 0 800 600">
<circle cx="400" cy="300" r="250" stroke-width="20" stroke="#f00" fill="#ff0" />
</svg>
The viewBox
defines a co-ordinate space. In this example, an 800
× 600
area starting at position 0,0
has a yellow circle with a red border and a 250
unit radius drawn in the center:
These are the benefits of vectors over bitmaps:
SVG images are ideal for logos, charts, icons, and simpler diagrams. Only photographs are generally impractical, although SVGs have been used for lazy-loading placeholders.
#css #web-development #programming #developer