search
HomeWeb Front-endCSS TutorialHow to Simplify SVG Code Using Basic Shapes

How to Simplify SVG Code Using Basic Shapes

There are many ways to deal with icons, but the best approach always includes SVG, whether it is implemented inline or as a link to an image file. This is because they are "drawn" in code, making them flexible, adaptable and scalable in any environment.

However, when using SVG, it is always possible to include a lot of unnecessary code . In some cases, the code for inlined SVG can be so long that the document scrolls longer and is uncomfortable to use, and yes, a little heavier than it needs to be.

We can use<use></use> Elements reuse code blocks, or apply native variables to manage our SVG styles in one place. Or, if we work in a server-side environment, we can always add some PHP (or similar) to extract the contents of the SVG file instead of putting it in directly.

This is all good, but wouldn't it be nice if we could solve this problem at the file level instead of resorting to a code-based approach? I want to focus on a different perspective: how to make the same graph with less code using basic shapes . This way, we can get the benefits of smaller, more controllable and semantic icons in the project without sacrificing quality or visual changes. I'll cover different examples, explore the code for common icons and how to repaint them using some of the simplest SVG shapes we can make.

Here are the icons we will deal with:

Let's look at the basic shapes we can use to make these icons that keep the code small and simple.

Shh! Here is a longer list of simple icons I created on holasvg.com! After reading this article, you will know how to modify them and make them yours.

use<line></line> Element simplified close icon

Here is the code for the "close" or "cross" icon downloaded from flaticon.com and built by pixel-perfect:

In this example, everything happens<path></path> Inside, there are many commands and parameters in the data attribute (d). What this SVG does is track the shape from its boundaries.

If you are familiar with Illustrator, this is equivalent to drawing two separate lines, converting them into shapes, and then combining the two with a path finder to create a composite shape.

<path></path> Elements allow us to draw complex shapes, but in this case we can create the same figure with two lines while maintaining the same appearance:

<code><svg height="50" overflow="visible" stroke="black" stroke-linecap="round" stroke-width="10" viewbox="0 0 50 50" width="50" xmlns="http://www.w3.org/2000/svg">
<line x1="0" x2="50" y1="0" y2="50"></line>
<line x1="50" x2="0" y1="0" y2="50"></line></svg></code>

We first define a viewBox, from 0,0 to 50,50. You can choose any size you like; the SVG will always scale well to any width and height you define. To simplify operations, in this case I also defined 50 units of inline width and height, which avoids additional calculations in the drawing.

To use<line></line> Element, we need to declare the coordinates of the first point of the line and the coordinates of the last point. In this example, we start with x=0 y=0 and end with x=50 y=50.

This is what the code looks like:

<code><line x2="50" y2="50"></line></code>

The second line will start with x=50 y=0 and end with x=0 y=50:

<code><line x1="50" y2="50"></line></code>

SVG strokes have no color by default - that's why we add black values ​​to the stroke attribute. We also provide 10 units of width for the stroke-width property and set the stroke-linecap to the circle value to copy those rounded corners of the original design. These properties are added directly to<svg></svg> in the tag, so both lines will inherit them.

Since the stroke is 10 units larger than its default size 1 unit, the viewBox may crop the line. We can move the point 10 units into the viewBox, or add overflow=visible to the style.

Values ​​equal to 0 can be deleted because 0 is the default value. This means that two lines end up with only two very small lines of code:

<code><line x2="50" y2="50"></line><line x1="50" y2="50"></line></code>

Just by<path></path> Change to<line></line> ,We not only create a smaller SVG file, but also create a more semantic and controllable code block, which makes any future maintenance easier. The visual effect is exactly the same as the original image.

Same cross, different codes.

use<circle></circle> and<path></path> Element simplified clock icon

I got this clock icon example from barracuda in The Noun Project:

This shape is also used<path></path> Draw, but we also have many namespace and XML directives related to the software and file license used, which we can delete without affecting SVG. Can you tell which illustration editor to use to create the icon?

Let's recreate this from scratch using a circle and a path with simpler commands. Again, we need to start with a viewBox, this time from 0,0 to 100,100, and the width and height match those units.

<code><svg fill="none" height="100" stroke="black" stroke-linecap="round" stroke-linejoin="round" stroke-width="10" viewbox="0 0 100 100" width="100" xmlns="http://www.w3.org/2000/svg"><circle cx="50" cy="50" r="40"></circle><path d="M50 25V50 H75"></path></svg></code>

we will<svg></svg> The style in the label remains the same as the previous icon. fill defaults to black, so we need to explicitly assign it a none value to it in order to delete it. Otherwise, the circle will have a pure black fill, obstructing other shapes.

To draw<circle></circle> , we need to indicate the center point where the radius will be located. We can do this with cx (center x) and cy (center y). Then r (radius) will declare how big our circle is. In this example, the radius is slightly smaller than the viewBox, so it won't be cropped when the stroke width is 10 units.

What's going on with all these letters? Check out Chris Coyier's illustration guide for an introduction to SVG grammar.

We can use the clock pointer<path></path> , because it has some very useful and simple drawing commands. In d (data), we have to start with the M (move to) command followed by the coordinates we will start drawing, in this case 50,25 (near the top center of the circle).

After the V (vertical) command, we only need one value, because we can only move up or down using negative or positive numbers. A positive number will move downward. The same is true for H (level), followed by a positive number 75, which will be drawn to the right. All commands are capitalized, so the number we choose will be the points in the grid. If we decide to use lowercase letters (relative commands), the number will be the number of units we move in one direction, not the absolute point in the coordinate system.

Same clock, different codes.

use<rect></rect> and<polyline></polyline> Element simplified envelope icon

I drew the envelope icon in Illustrator without extending the original shape. Here is the code obtained from the export:

Illustrator provides some SVG options for exporting graphics. I selected "Style Element" in the "CSS Properties" drop-down menu so that I can have a tag with the category that I might want to move into the CSS file. Of course, there are many ways to apply SVG styles.

We already have some basic shapes in this code! I didn't choose the "Shape to Path" option in Illustrator, which helps a lot here. We can further optimize it using SVGOMG to remove comments, XML directives and unnecessary data such as empty elements. We can manually delete additional extras from there if needed.

We already have something simpler:

<code><svg version="1.1" viewbox="0 0 310 190" x="0" xml:space="preserve" xmlns="http://www.w3.org/2000/svg" y="0">
 .st0{fill:none;stroke:#000;stroke-width:10;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:10}
<rect height="180" width="300" x="5" y="5"></rect>
<polyline points="5 5 155 110 305 5"></polyline></svg></code>

We can delete more content without affecting the visual appearance of the envelope, including:

  • version="1.1" (deprecated since SVG 2)
  • (This has no meaning or purpose)
  • x="0" (this is a default value)
  • y="0" (this is a default value)
  • xml:space="preserve" (deprecated since SVG 2)
<code><svg viewbox="0 0 310 190" xmlns="http://www.w3.org/2000/svg">
 .st0{fill:none;stroke:#000;stroke-width:10;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:10}
  
<rect height="180" width="300" x="5" y="5"></rect>
<polyline points="5 5 155 110 305 5"></polyline></svg></code>

If we really want to be very aggressive, we can move the CSS styles into a separate stylesheet.

<rect></rect> Need a starting point where we will expand the width and height from there, so let's use x="5" and y="5" as our top left corner points. From there, we will create a rectangle with a width of 300 units and a height of 180 units. Just like the clock icon, we will use 5,5 as the starting point because we have a 10-unit stroke that will be cropped if the coordinates are at 0,0.

<polyline></polyline> Similar to<line></line> , but this element always defines an enclosed shape. Here is an example directly from MDN:

Remember the circles we drew for the clock icon before? Replace r (radius) with rx and ry. Now you have two different radius values. Here is another example from MDN:

Summarize

We covered a lot of content in a short period of time! While we use examples to demonstrate the process of optimizing SVG, I hope you get the following from this post:

  • Remember that compression starts with the way SVG is drawn in the illustration software.
  • Use available tools such as SVOMG to compress SVG.
  • Manually delete unnecessary metadata if necessary.
  • Replace complex paths with basic shapes.
  • <use></use> Is a great way to "inline" SVGs and build your own reusable icon library.

How many icons can be created by combining these basic shapes?

I'm making my list on holasvg.com/icons, and I'm going to keep uploading more icons and features here, now you know how to easily modify them by changing a few numbers. Keep going, let them be yours!

The above is the detailed content of How to Simplify SVG Code Using Basic Shapes. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
@keyframes CSS: The most used tricks@keyframes CSS: The most used tricksMay 08, 2025 am 12:13 AM

@keyframesispopularduetoitsversatilityandpowerincreatingsmoothCSSanimations.Keytricksinclude:1)Definingsmoothtransitionsbetweenstates,2)Animatingmultiplepropertiessimultaneously,3)Usingvendorprefixesforbrowsercompatibility,4)CombiningwithJavaScriptfo

CSS Counters: A Comprehensive Guide to Automatic NumberingCSS Counters: A Comprehensive Guide to Automatic NumberingMay 07, 2025 pm 03:45 PM

CSSCountersareusedtomanageautomaticnumberinginwebdesigns.1)Theycanbeusedfortablesofcontents,listitems,andcustomnumbering.2)Advancedusesincludenestednumberingsystems.3)Challengesincludebrowsercompatibilityandperformanceissues.4)Creativeusesinvolvecust

Modern Scroll Shadows Using Scroll-Driven AnimationsModern Scroll Shadows Using Scroll-Driven AnimationsMay 07, 2025 am 10:34 AM

Using scroll shadows, especially for mobile devices, is a subtle bit of UX that Chris has covered before. Geoff covered a newer approach that uses the animation-timeline property. Here’s yet another way.

Revisiting Image MapsRevisiting Image MapsMay 07, 2025 am 09:40 AM

Let’s run through a quick refresher. Image maps date all the way back to HTML 3.2, where, first, server-side maps and then client-side maps defined clickable regions over an image using map and area elements.

State of Devs: A Survey for Every DeveloperState of Devs: A Survey for Every DeveloperMay 07, 2025 am 09:30 AM

The State of Devs survey is now open to participation, and unlike previous surveys it covers everything except code: career, workplace, but also health, hobbies, and more. 

What is CSS Grid?What is CSS Grid?Apr 30, 2025 pm 03:21 PM

CSS Grid is a powerful tool for creating complex, responsive web layouts. It simplifies design, improves accessibility, and offers more control than older methods.

What is CSS flexbox?What is CSS flexbox?Apr 30, 2025 pm 03:20 PM

Article discusses CSS Flexbox, a layout method for efficient alignment and distribution of space in responsive designs. It explains Flexbox usage, compares it with CSS Grid, and details browser support.

How can we make our website responsive using CSS?How can we make our website responsive using CSS?Apr 30, 2025 pm 03:19 PM

The article discusses techniques for creating responsive websites using CSS, including viewport meta tags, flexible grids, fluid media, media queries, and relative units. It also covers using CSS Grid and Flexbox together and recommends CSS framework

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.