Home > Web Front-end > CSS Tutorial > How to Arrange Icons in a Circle Using CSS and JavaScript?

How to Arrange Icons in a Circle Using CSS and JavaScript?

Patricia Arquette
Release: 2024-12-24 08:04:10
Original
528 people have browsed it

How to Arrange Icons in a Circle Using CSS and JavaScript?

Position Icons into Circle with CSS and JavaScript

Overview

Achieving the desired effect of positioning multiple images in a circle requires both CSS and JavaScript.

CSS for Positioning

To position the images in a circle, CSS transforms are necessary. Each image should be placed in the center of the containing element and then translated along the X-axis by half the width of the container. The following code demonstrates the CSS required:

.container {
  width: 24em;
  height: 24em;
  position: relative;
}

.icon {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
Copy after login

JavaScript for Distribution

While CSS positions the images, JavaScript is used to distribute them evenly around the circle. This involves calculating the angle between each image and rotating it accordingly. The following code demonstrates this:

const container = document.querySelector('.container');
const icons = document.querySelectorAll('.icon');

const containerWidth = container.getBoundingClientRect().width;
const containerHeight = container.getBoundingClientRect().height;
const iconWidth = icons[0].getBoundingClientRect().width;
const iconHeight = icons[0].getBoundingClientRect().height;

icons.forEach((icon, index) => {
  const angle = (Math.PI * 2) / icons.length;
  const transformString = `rotate(${angle * index}rad) translate(${containerWidth / 2 - iconWidth / 2}px, ${containerHeight / 2 - iconHeight / 2}px)`;
  icon.style.transform = transformString;
});
Copy after login

Conclusion

By combining the CSS for positioning and the JavaScript for distribution, you can effectively place several images into a circle and maintain their clickable functionality.

The above is the detailed content of How to Arrange Icons in a Circle Using CSS and JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template