I got motivated by Bytes #293 main thing about HTML. Their motivation came from State of HTML 2023 survey (and money... but let's leave the sponsored section from mailing).
It appears that
Entry point
If you are not familiar with this stuff at all, I can help with a bunch of links for the start. After that, nothing will change but you will know something more about svg
ˉ_(ツ)_/ˉ
- https://developer.mozilla.org/en-US/docs/Learn/HTML/Multimedia_and_embedding/Adding_vector_graphics_to_the_Web
- https://developer.mozilla.org/en-US/docs/Web/SVG/Tutorial/Introduction
- SVG tutorial from MDN: https://developer.mozilla.org/en-US/docs/Web/SVG/Tutorial/Getting_Started
Tl;DR
SVG elements are vector graphic elements. This can be understood as a bunch of geometric figures represented in characters. You can create one for example with Adobe Illustrator or Inkscape as a free alternative.
Starting point
From people's answers, we can see a few patterns. I won't pick any specific one but I will try to share some knowledge around those topics so you can find here some tips&tricks, sharing experience and other common knowledge around this topic.
I will skip the SVG sprites topic like this example. It's a separate topic and is not very connected to the svg tag. I can just agree that you could still find a few rare use cases for them.
File syntax
A proper SVG file should be a representation of the mentioned geometric figures. It's very easy to check if our icon is prepared in the right format by the designer or website where you are taking it.
Wrong example:
<svg ...><image link:href="data:image/png;base64 .../>
Expected syntax:
<svg><g><path r=""/><circle /></g></svg>
During my career, I stepped into this a few times. It's worth to remember that. It happens when you take raster graphics, import them to a vector graphic program and try to export them in .svg extension. It does not magically convert your image to a vector graphic.
Notable SVG tags
I can present you a cheat sheet for most generic svg elements.
Tag | Description | Animated attributes |
---|---|---|
used for grouping elements | - | |
main tag for your actual icon. Avoid modifying the d="" attribute on your own ? It is possible but be careful with that. Grab a link with an explanation for each character group. To animate your path use animateMotion tag | - | |
Basic rectangle shape in SVG. Simple as that | ? | |
Simple as that. The line between two points. Don't mistake with the stroke attribute! It can also be used on the line tag. | ? | |
You can think about it as an enhancement version of the g tag but it keeps the elements inside invisible for later use with, let's guess it... use tag | - | |
Next basic shape. Be careful as the size is defined by radius and you position your circle with cx and cy attributes. | ? | |
Let's call it a custom shape. They are connected straight lines where the last point connects to the first point. | ? | |
Very similar to the previous one but with a notable difference. The last point doesn't need to be connected to the first point. | ? |
Please note those are only a few selected SVG elements. I have just described the most common ones. There are a lot more available for you to use. A full list can be found here.
Sizing and positioning
As we are now familiar with some of the common svg tags we can go into the next paragraph of modifying the base parameters of our icon.
Let's say we work with a young designer. He/She doesn't fully know how to prepare things for the web yet as you do. As a result, you sometimes get slightly different sizes of an icon with missing cut padding on the sides.
good one | wrong one |
---|---|
![]() |
![]() |
Classic case. I know we should have a quick call with a designer and clarify this but we want to learn some svg here. We are not doing that in this scenario. We can fix it ourselves.
From the code perspective, it's all about attributes. The original SVG cross file looks like this:
<svg ...><image link:href="data:image/png;base64 .../>
Results in:
Almost what we want! Let's dig further into how we can preserve padding as in the first icon.
We have 2 options. We can keep the same viewBox value or we can adjust each width, height, x and y value on every nested tag.
The first option seems simple and it works for us quite well but there might be a catch. In my case, I had this weird transform attribute on my group tag.
<svg><g><path r=""/><circle /></g></svg>
Now our icon size is adjustable. Please note that it's vector graphics so we don't lose icon quality after resizing.
So why is viewBox so important?
It's the key when we want to correctly scale or set a certain position to our icon. It has 4 arguments viewBox="min-x min-y width height".
For example, viewBox="0 0 100 100" means the top-left corner is at (0, 0) and the viewBox is 100 units wide and 100 units high.
That means you have to adjust your icon x and y attributes after changing viewBox as they are set according to their value.
Managing colors and fill
Different icons allow different fill. Of course, it can be as easy as adding a color style but that's a rookie-level type of code.
Real developers are adding fill-rule="evenodd" to the main element and deleting all other manual fill attributes from tags ?
You may wonder why.
I will provide the shortest possible answer to this. To freely customize our icon colours with one line of code straight from our IDE.
How is that possible you might ask.
If you are dealing with a simple icon from your company's design system you should be able to import only one icon. Modifiers or duplications in size or colour are not necessary.
From a code perspective, you just have to add fill on the svg element like you would normally do with for example colour attribute.
<?xml version="1.0" encoding="UTF-8" standalone="no"?> <!-- Created with Inkscape (http://www.inkscape.org/) --> <svg width="93.582886" height="93.582893" viewBox="0 0 24.760471 24.760474" version="1.1" > <p>This is our raw svg exported from Inkscape. There are a few other things to fix, bear with me so we can fix them.</p> <p>We know that 200px image is our goal. Here we have some ugly width/height values on the main svg tag.</p> <p>Simply:<br> </p> <pre class="brush:php;toolbar:false"><svg - width="93.582886" + width="200" - height="93.582893" + height="200"
There is a catch for evenodd value which applies when you are drawing polygons or paths. It will fill only the inside of crossing path segments.
Consider analyzing this example in case you struggle with it.
So in the case of our cross icon, it will result in something like this:
Optimizing
Before we publish our icon to the web (or right after we download it from Figma) we should ensure it's properly optimized. This one is very important. I have caught and been caught way too many times during code review on this last mile.
SVGO (or SVGR for react) is making it a very easy process. Behind the scenes, it mostly deletes all unnecessary stuff for us.
In general, it is a go-to tool. Either you want to integrate it with your bundler or use it from CLI. It's ready to use right after installation as we get default preset configured out of the box.
Note: You can overwrite the default preset if you really want to. Check configuration in the project README and plugin list in docs
Result
The final icon code looks like this:
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 50 50"><g fill-rule="evenodd"><path d="M9 24h32v3H9z"> <p>We have reduced the size from 871 bytes with raw icon exported from inkspace to only 322 bytes.</p> <h2> Pain with animations </h2> <p>The last topic that is bitter-sweet for me. It was brought in the survey answers a couple of times as well. I don't know better ways to do it except using Lottie or manually animating elements of SVG in CSS. The second option is absolute torture when you have more than 5 elements to animate.</p> <p>Of course, it is possible and we can do it but being honest, there are more interesting things to do ?</p> <p>Suppose you are still curious about how to do it. I'm leaving a link to a great article here. It should convince you that it requires patience and takes more than 5 minutes. I wonder if an AI bot can help you with that! If yes, maybe it's a bit less painful.</p> <p>That's it for now.<br> Hopefully, you took something from this post and have a nice day ?</p>
The above is the detailed content of SVG hacks for you. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

There are three common ways to initiate HTTP requests in Node.js: use built-in modules, axios, and node-fetch. 1. Use the built-in http/https module without dependencies, which is suitable for basic scenarios, but requires manual processing of data stitching and error monitoring, such as using https.get() to obtain data or send POST requests through .write(); 2.axios is a third-party library based on Promise. It has concise syntax and powerful functions, supports async/await, automatic JSON conversion, interceptor, etc. It is recommended to simplify asynchronous request operations; 3.node-fetch provides a style similar to browser fetch, based on Promise and simple syntax

JavaScript data types are divided into primitive types and reference types. Primitive types include string, number, boolean, null, undefined, and symbol. The values are immutable and copies are copied when assigning values, so they do not affect each other; reference types such as objects, arrays and functions store memory addresses, and variables pointing to the same object will affect each other. Typeof and instanceof can be used to determine types, but pay attention to the historical issues of typeofnull. Understanding these two types of differences can help write more stable and reliable code.

Which JavaScript framework is the best choice? The answer is to choose the most suitable one according to your needs. 1.React is flexible and free, suitable for medium and large projects that require high customization and team architecture capabilities; 2. Angular provides complete solutions, suitable for enterprise-level applications and long-term maintenance; 3. Vue is easy to use, suitable for small and medium-sized projects or rapid development. In addition, whether there is an existing technology stack, team size, project life cycle and whether SSR is needed are also important factors in choosing a framework. In short, there is no absolutely the best framework, the best choice is the one that suits your needs.

Hello, JavaScript developers! Welcome to this week's JavaScript news! This week we will focus on: Oracle's trademark dispute with Deno, new JavaScript time objects are supported by browsers, Google Chrome updates, and some powerful developer tools. Let's get started! Oracle's trademark dispute with Deno Oracle's attempt to register a "JavaScript" trademark has caused controversy. Ryan Dahl, the creator of Node.js and Deno, has filed a petition to cancel the trademark, and he believes that JavaScript is an open standard and should not be used by Oracle

CacheAPI is a tool provided by the browser to cache network requests, which is often used in conjunction with ServiceWorker to improve website performance and offline experience. 1. It allows developers to manually store resources such as scripts, style sheets, pictures, etc.; 2. It can match cache responses according to requests; 3. It supports deleting specific caches or clearing the entire cache; 4. It can implement cache priority or network priority strategies through ServiceWorker listening to fetch events; 5. It is often used for offline support, speed up repeated access speed, preloading key resources and background update content; 6. When using it, you need to pay attention to cache version control, storage restrictions and the difference from HTTP caching mechanism.

Promise is the core mechanism for handling asynchronous operations in JavaScript. Understanding chain calls, error handling and combiners is the key to mastering their applications. 1. The chain call returns a new Promise through .then() to realize asynchronous process concatenation. Each .then() receives the previous result and can return a value or a Promise; 2. Error handling should use .catch() to catch exceptions to avoid silent failures, and can return the default value in catch to continue the process; 3. Combinators such as Promise.all() (successfully successful only after all success), Promise.race() (the first completion is returned) and Promise.allSettled() (waiting for all completions)

JavaScript array built-in methods such as .map(), .filter() and .reduce() can simplify data processing; 1) .map() is used to convert elements one to one to generate new arrays; 2) .filter() is used to filter elements by condition; 3) .reduce() is used to aggregate data as a single value; misuse should be avoided when used, resulting in side effects or performance problems.

JavaScript's event loop manages asynchronous operations by coordinating call stacks, WebAPIs, and task queues. 1. The call stack executes synchronous code, and when encountering asynchronous tasks, it is handed over to WebAPI for processing; 2. After the WebAPI completes the task in the background, it puts the callback into the corresponding queue (macro task or micro task); 3. The event loop checks whether the call stack is empty. If it is empty, the callback is taken out from the queue and pushed into the call stack for execution; 4. Micro tasks (such as Promise.then) take precedence over macro tasks (such as setTimeout); 5. Understanding the event loop helps to avoid blocking the main thread and optimize the code execution order.
