Put items evenly on a circle's circumference - Kodhus

Put items evenly on a circle’s circumference

Introduction

In this article we are going to learn how we can put items on a circle. We will be utilizing css transform to put items on the circumference of a circle.

Idea

We need to calculate the angle between the items that will ultimately reside on the circumference of the circle based on the number of items. So basically knowing that a circle is 360 degree in total we just divide 360 by that number. So let’s say we want to put 4 elements on the circle, the angle will be 360/4 = 90.

Then we use css transform rotate and css transform translate to put those on their appropriate place. The rotate will rotate the item on the appropriate direction and then translate will move the item on the circumference.

Let’s take a look at a simple code.

 

Markup (Html)

<div class="circle">
  <div class="tick"></div>
  <div class="tick"></div>
  <div class="tick"></div>
  <div class="tick"></div>
</div>

CSS

Now Let’s style our div with the class circle. I will give the radius of the circle 100px which means that I will give the div the width and height equal to 200px(Radius is half of the width or height!). I will also give it a background colour so that we see something!

.circle {
  width: 200px;
  height: 200px;
  background: pink;
  border-radius: 50%;
}

Now I will style each tick class to be small circles like in a watch face! What I have in mind is circles of size 10px. I also set the position to absolute so that we can easily move them using css transform property! We need to first move all ticks to the center of the circle by using left and top properties set to 50% and then since each tick has width and height equal to 10px, we use margin-left and margin-top with negative values of half of the size of each to center them exactly in the middle of the circle.

.circle .tick {
  width: 10px;
  height: 10px;
  background: #000;
  position: absolute;
  border-radius: 50%;
  left: 50%;
  top: 50%;
  margin-left: -5px;
  margin-top: -5px;
}

Finally using transform property we put the divs with class tick on the circumference of the parent circle div.

.circle .tick:nth-child(1) {
  transform: rotate(0deg) translate(100px);
}
.circle .tick:nth-child(2) {
  transform: rotate(90deg) translate(100px);
}
.circle .tick:nth-child(3) {
  transform: rotate(180deg) translate(100px);
}
.circle .tick:nth-child(4) {
  transform: rotate(270deg) translate(100px);
}

Let’s take a look at the final result!

In the next tutorial, we will use sass to parameterize this to create awesome results. For now take a look at the following watch face prototype which is done in sass preprocessor:

Watch face using sass

Have a great day!

Share if you liked it: Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedIn

Leave a Reply

Your email address will not be published. Required fields are marked *

Share
Tweet
+1
Share