search
HomeWeb Front-endCSS TutorialCreating UI Components in SVG

SVG empowers web interface construction: Exploring the infinite possibilities of custom UI components

Creating UI Components in SVG

SVG shows great potential in web interface construction. It may be a bit difficult to learn SVG, but its original intention is to create shapes, while supporting elements such as text, links and ARIA tags. Although CSS can also achieve some of the same effects, CSS is more difficult in precise positioning, especially cross-windows and responsive development.

What is unique about SVG is that its positioning is based on a coordinate system, similar to the game "battleship". This means that determining the location of elements, how they are drawn, and relative positions between elements are very intuitive. CSS positioning is mainly used for layout, which is good because the elements in the document stream correspond to each other. But if you want to create specific components with overlapping and precise placement of elements, this feature actually increases the difficulty.

Once you master SVG, you can draw any graphics and make it scaleable on any device. Even this website uses SVG to create custom UI elements, such as the avatar (metadata!).

This article will not cover the entire content of SVG (you can learn some basics here, here, here, and here), but to illustrate the possibilities SVG brings to UI component development, let's discuss a specific use case and break down the idea of ​​building custom components.

Timeline Task List Component

Recently, I worked on a project with the Netlify team. We need to show viewers where they are currently watching videos in the course video series. In other words, we need to create something like a to-do list, but show overall progress when the project is finished. (We created a free space-themed learning platform, which is very cool. Yes, I used the word "very cool".)

The effects are as follows:

How should we achieve it? I'll show the Vue and React examples separately so you can understand how it is implemented in both frameworks.

Vue version

We decided to build the platform using Next.js (to try out our own Netlify Next build plugin), but I am more familiar with Vue, so I wrote the initial prototype in Vue and then ported to React.

Complete CodePen demo: [CodePen link should be inserted here]

Let's analyze the code step by step. First, this is a single file component (SFC), so template HTML, reactive scripts, and scope styles are all encapsulated in one file.

We store some virtual tasks in data, including whether each task has been completed. We will also create a method that can be called on the click command to switch states.

 export default {
  data() {
    return {
      tasks: [
        {
          name: 'thing',
          done: false
        },
        // ...
      ]
    };
  },
  methods: {
    selectThis(index) {
      this.tasks[index].done = !this.tasks[index].done
    }
  }
};

Now, we want to create an SVG with a flexibly adjusting viewBox according to the number of elements. We also need to tell the screen reader that this is a demo element and we will provide the title with the unique ID "timeline". (Get more information on creating accessible SVGs.)

<template>
  <div>
    <div>
      <svg :viewbox="`0 0 30 ${tasks.length * 50}`" aria-labelledby="timeline" fill="white" role="presentation" stroke="currentColor" width="30" xmlns="http://www.w3.org/2000/svg">
        <title>timeline element</title>
      </svg>
    </div>
  </div>
</template>

stroke is set to currentColor for flexibility - if you want to reuse the component in multiple locations, it will inherit the colors used by the encapsulated div.

Next, inside the SVG, we want to create a vertical line with the same length as the task list. The lines are very simple. We have x1 and x2 values ​​(the line draws on the x-axis), and similarly, y1 and y2.

<line :y1="num2" :y2="tasks.length * num1 - num2" x1="10" x2="10"></line>

The x-axis always stays at 10 because we are drawing lines from top to bottom, not from left to right. We store two numbers in data: the spacing we want, i.e. num1, and the margin we want, i.e. num2.

 data() {
  return {
    num1: 32,
    num2: 15,
    // ...
  }
}

The y-axis starts with num2, subtracting the margin from the end. tasks.length multiplied by the spacing num1.

Now, we need a circle on the line. Each circle indicates whether the task has been completed. Each task requires a circle, so we will use v-for and the unique key, i.e. index (it is safe to use here because they will never be reordered). We connect the click directive to our method and pass the index as a parameter.

Circles in SVG are composed of three properties. The center of the circle is located in cx and cy, and we then draw the radius with r. Like lines, cx starts at 10. The radius is 4 because it is readable at this scale. cy will be spaced like a line: index times spacing (num1), plus margins (num2).

Finally, we will set the padding using the ternary operator. If the task has been completed, populate the currentColor. If not, fill in white (or any background color). For example, this could be used to use a prop fill that passes the background, which contains light and dark circles.

<circle :cy="i * num1   num2" :fill="task.done ? 'currentColor' : 'white'" :key="task.name" cx="10" r="4" v-for="(task, i) in tasks"></circle>

Finally, we use a CSS grid to align divs containing the task name. The layout is roughly the same, we iterate through the task and bind it to the same click event to switch the completed state.

<template>
  <div>
    <div :key="task.name" v-for="(task, i) in tasks">
      {{ task.name }}
    </div>
  </div>
</template>

React version

This is the final result of the React version. We are working on opening source so that you can view the full code and its history. Here are some modifications:

  • We use CSS module instead of SFC in Vue
  • We import Next.js links, so instead of switching the "completed" state, we take the user to a dynamic page in Next.js
  • The tasks we use are actually the stages of the course—or what we call “tasks”—where they are passed in, not held by components.

Most other functions are the same :)

 // React code snippet (the complete React code should be pasted here)

Final version

You can view the final running version here: [The final version link should be inserted here]

The component is flexible enough to accommodate lists of different sizes, multiple browsers, and responsive resizing. It also enables users to better understand their progress in the course.

But this is just a component. You can create as many UI elements as you like: knobs, controls, progress indicators, loaders...the possibilities are endless. You can style it with CSS or inline styles, you can update it based on prop, context or reactive data, with endless possibilities! I hope this opens up some ideas on how to develop more engaging Web UI elements.

The above is the detailed content of Creating UI Components in SVG. 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
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

What does the CSS box-sizing property do?What does the CSS box-sizing property do?Apr 30, 2025 pm 03:18 PM

The article discusses the CSS box-sizing property, which controls how element dimensions are calculated. It explains values like content-box, border-box, and padding-box, and their impact on layout design and form alignment.

How can we animate using CSS?How can we animate using CSS?Apr 30, 2025 pm 03:17 PM

Article discusses creating animations using CSS, key properties, and combining with JavaScript. Main issue is browser compatibility.

Can we add 3D transformations to our project using CSS?Can we add 3D transformations to our project using CSS?Apr 30, 2025 pm 03:16 PM

Article discusses using CSS for 3D transformations, key properties, browser compatibility, and performance considerations for web projects.(Character count: 159)

How can we add gradients in CSS?How can we add gradients in CSS?Apr 30, 2025 pm 03:15 PM

The article discusses using CSS gradients (linear, radial, repeating) to enhance website visuals, adding depth, focus, and modern aesthetics.

What are pseudo-elements in CSS?What are pseudo-elements in CSS?Apr 30, 2025 pm 03:14 PM

Article discusses pseudo-elements in CSS, their use in enhancing HTML styling, and differences from pseudo-classes. Provides practical examples.

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

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.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.