Wednesday 7 April 2021

Choosing between CSS and SVG (Part 1/2)

CSS and SVG are both non-programming languages that are part of web development. They can be embedded into HTML to create great visual effects.

While there's a certain amount of overlap, for the most part their uses cases are quite separate and distinct. SVG is mostly used for graphics, and CSS for layout. But there will be times when either CSS or SVG could do the job, and the inevitable question would be - which should you use?

Here, I'm going to take a look at each, and outline the situations where you should choose one over the other.

SVG (Scalable Vector Graphics)

I started learning SVGs while using D3.js, a Data Visualization JavaScript library. And soon fell in love with the sheer amount of artistic freedom it gave me.

Use Case. SVG is used for graphics. Be it charts and graphs, icons or fancy animations, SVG works great. CSS can do the same thing, yes... and in simple cases perhaps even outperforms SVGs.

But here's the thing: CSS graphics are mostly rectangular and square divs. Even ovals and circles are rectangular or square divs with rounded corners. It's still possible to render complex shapes from CSS, but you have to jump through an awful lot of hoops to do it. Don't get me wrong; it can be fun. But also pretty frustrating.

SVG, on the other hand, has a path tag that was made for complex shapes. Add Bezier Curves to the mix and you have a very potent tool. Animations and transformations are also relatively simple to create.

Easier to draw in SVG.

Using SVG for intricate graphic work is a much more attractive option than CSS, at least where capability and ease of use is concerned.

Learning Curve. Chances are that you already know HTML. And if you do, learning SVGs is a breeze. Everything about embedding SVGs in HTML5 is about XML tags. Circles, ellipses, rectangles, lines, paths, animations... all XML tags with attributes to specify appearance and behavior. And in case you don't feel like learning all of that, there are always SVG generators.

You also need to know HTML in order to use CSS, but that's where the resemblance ends. CSS is nothing like HTML. Some parts of CSS are easy enough to master. The rest is hellishly difficult, especially when you're trying to use CSS to do the things that SVG does.

Purely absolute positioning.
Anyone who has ever used CSS and been frustrated about the differences between relative and absolute positioning, will love this part about SVGs. Just about everything is absolutely positioned from the top left corner of the SVG. There are no questions about relative positioning from one element to another. Overlapping is also easier because whatever tag is declared last, always goes on top.

Next

We'll take a look at what CSS does better.

No comments:

Post a Comment