Making a Clock with the New CSS sin() and cos() Trigonometry Capabilities | CSS-Tips

CSS trigonometry features are right here! Effectively, they’re in case you’re utilizing the newest variations of Firefox and Safari, that’s. Having this form of mathematical energy in CSS opens up a complete bunch of prospects. On this tutorial, I assumed we’d dip our toes within the water to get a really feel for a few the newer features: sin() and cos().

There are different trigonometry features within the pipeline — together with tan() — so why focus simply on sin() and cos()? They occur to be good for the concept I take into account, which is to position textual content alongside the sting of a circle. That’s been lined right here on CSS-Tips when Chris shared an method that makes use of a Sass mixin. That was six years in the past, so let’s give it the bleeding edge therapy.

 

Right here’s what I take into account. Once more, it’s solely supported in Firefox and Safari in the meanwhile:

So, it’s not precisely like phrases forming a round form, however we’re inserting textual content characters alongside the circle to kind a clock face. Right here’s some markup we will use to kick issues off:

<code><div class="clock">
  <div class="clock-face">
    <time datetime="12:00">12</time>
    <time datetime="1:00">1</time>
    <time datetime="2:00">2</time>
    <time datetime="3:00">3</time>
    <time datetime="4:00">4</time>
    <time datetime="5:00">5</time>
    <time datetime="6:00">6</time>
    <time datetime="7:00">7</time>
    <time datetime="8:00">8</time>
    <time datetime="9:00">9</time>
    <time datetime="10:00">10</time>
    <time datetime="11:00">11</time>
  </div>
</div></code>

Subsequent, listed below are some tremendous primary types for the .clock-face container. I made a decision to make use of the  tag with a datetime attribute.

<code>.clock {
  --_ow: clamp(5rem, 60vw, 40rem);
  --_w: 88cqi;
  aspect-ratio: 1;
  background-color: tomato;
  border-radius: 50%;
  container-type: inline;
  show: grid;
  top: var(--_ow);
  place-content: middle;
  place: relative;
  width var(--_ow);
}</code>

I embellished issues a bit in there, however solely to get the fundamental form and background coloration to assist us see what we’re doing. Discover how we save the width worth in a CSS variable. We’ll use that later. Not a lot to take a look at to this point:

It seems like some form of fashionable artwork experiment, proper? Let’s introduce a brand new variable, --_r, to retailer the circle’s radius, which is the same as half of the circle’s width. This fashion, if the width (--_w) modifications, the radius worth (--_r) will even replace — thanks to a different CSS math perform, calc():

<code>.clock {
  --_w: 300px;
  --_r: calc(var(--_w) / 2);
  /* remainder of types */
}</code>

Now, a little bit of math. A circle is 360 levels. We’ve got 12 labels on our clock, so need to place the numbers each 30 levels (360 / 12). In math-land, a circle begins at 3 o’clock, so midday is definitely minus 90 levels from that, which is 270 levels (360 - 90).

Let’s add one other variable, --_d, that we will use to set a diploma worth for every quantity on the clock face. We’re going to increment the values by 30 levels to finish our circle:

<code>.clock time:nth-child(1) { --_d: 270deg; }
.clock time:nth-child(2) { --_d: 300deg; }
.clock time:nth-child(3) { --_d: 330deg; }
.clock time:nth-child(4) { --_d: 0deg; }
.clock time:nth-child(5) { --_d: 30deg; }
.clock time:nth-child(6) { --_d: 60deg; }
.clock time:nth-child(7) { --_d: 90deg; }
.clock time:nth-child(8) { --_d: 120deg; }
.clock time:nth-child(9) { --_d: 150deg; }
.clock time:nth-child(10) { --_d: 180deg; }
.clock time:nth-child(11) { --_d: 210deg; }
.clock time:nth-child(12) { --_d: 240deg; }</code>

OK, now’s the time to get our fingers soiled with the sin() and cos() features! What we need to do is use them to get the X and Y coordinates for every quantity so we will place them correctly across the clock face.

The components for the X coordinate is radius + (radius * cos(diploma)). Let’s plug that into our new --_x variable:

<code>--_x: calc(var(--_r) + (var(--_r) * cos(var(--_d))));</code>

The components for the Y coordinate is radius + (radius * sin(diploma)). We’ve got what we have to calculate that:

<code>--_y: calc(var(--_r) + (var(--_r) * sin(var(--_d))));</code>

There are a couple of housekeeping issues we have to do to arrange the numbers, so let’s put some primary styling on them to ensure they’re completely positioned and positioned with our coordinates:

<code>.clock-face time {
  --_x: calc(var(--_r) + (var(--_r) * cos(var(--_d))));
  --_y: calc(var(--_r) + (var(--_r) * sin(var(--_d))));
  --_sz: 12cqi;
  show: grid;
  top: var(--_sz);
  left: var(--_x);
  place-content: middle;
  place: <a href="https://yourselfhood.com/an-overview-of-css-sizing-units-sitepoint/">absolute</a>;
  high: var(--_y);
  width: var(--_sz);
}</code>

Discover --_sz, which we’ll use for the width and top of the numbers in a second. Let’s see what we have now to this point.

Large tomato colored circle with off-centered hour number labels along its edge.

This positively seems extra like a clock! See how the top-left nook of every quantity is positioned on the appropriate place across the circle? We have to “shrink” the radius when calculating the positions for every quantity. We will deduct the dimensions of a quantity (--_sz) from the dimensions of the circle (--_w), earlier than we calculate the radius:

<code>--_r: calc((var(--_w) - var(--_sz)) / 2);</code>
Large tomato colored circle with hour number labels along its rounded edge.

Significantly better! Let’s change the colours, so it seems extra elegant:

A white clock face with numbers against a dark gray background. The clock has no arms.

We may cease proper right here! We achieved the aim of inserting textual content round a circle, proper? However what’s a clock with out arms to point out hours, minutes, and seconds?

Let’s use a single CSS animation for that. First, let’s add three extra parts to our markup,

<code><div class="clock">
  <!-- after <time>-tags -->
  <span class="arm seconds"></span>
  <span class="arm minutes"></span>
  <span class="arm hours"></span>
  <span class="arm middle"></span>
</div></code>

Then some widespread markup for all three arms. Once more, most of that is simply ensure that the arms are completely positioned and positioned accordingly:

<code>.arm {
  background-color: var(--_abg);
  border-radius: calc(var(--_aw) * 2);
  show: block;
  top: var(--_ah);
  left: calc((var(--_w) - var(--_aw)) / 2);
  place: absolute;
  high: calc((var(--_w) / 2) - var(--_ah));
  rework: rotate(0deg);
  transform-origin: backside;
  width: var(--_aw);
}</code>

We’ll use the similar animation for all three arms:

<code>@keyframes flip {
  to {
    rework: rotate(1turn);
  }
}</code>

The one distinction is the time the person arms take to make a full flip. For the hours arm, it takes 12 hours to make a full flip. The animation-duration property solely accepts values in milliseconds and seconds. Let’s persist with seconds, which is 43,200 seconds (60 seconds * 60 minutes * 12 hours).

<code>animation: flip 43200s infinite;</code>

It takes 1 hour for the minutes arm to make a full flip. However we would like this to be a multi-step animation so the motion between the arms is staggered reasonably than linear. We’ll want 60 steps, one for every minute:

<code>animation: flip 3600s steps(60, finish) infinite;</code>

The seconds arm is virtually the identical because the minutes arm, however the period is 60 seconds as an alternative of 60 minutes:

<code>animation: flip 60s steps(60, finish) infinite;</code>

Let’s replace the properties we created within the widespread types:

<code>.seconds {
  --_abg: hsl(0, 5%, 40%);
  --_ah: 145px;
  --_aw: 2px;
  animation: flip 60s steps(60, finish) infinite;
}
.minutes {
  --_abg: #333;
  --_ah: 145px;
  --_aw: 6px;
  animation: flip 3600s steps(60, finish) infinite;
}
.hours {
  --_abg: #333;
  --_ah: 110px;
  --_aw: 6px;
  animation: flip 43200s linear infinite;
}</code>

What if we need to begin on the present time? We want just a little little bit of JavaScript:

<code>const time = new Date();
const hour = -3600 * (time.getHours() % 12);
const minutes = -60 * time.getMinutes();
app.model.setProperty('--_dm', `${minutes}s`);
app.model.setProperty('--_dh', `${(hour+minutes)}s`);</code>

I’ve added id="app" to the clockface and set two new customized properties on it that set a detrimental animation-delay, as Mate Marschalko did when he shared a CSS-only clock. The getHours() methodology of JavaScipt’s Date object is utilizing the 24-hour format, so we use the the rest operator to transform it into 12-hour format.

Within the CSS, we have to add the animation-delay as properly:

<code>.minutes {
  animation-delay: var(--_dm, 0s);
  /* different types */
}

.hours {
  animation-delay: var(--_dh, 0s);
  /* different types */
}</code>

Only one thing more. Utilizing CSS @helps and the properties we’ve already created, we will present a fallback to browsers that don’t supprt sin() and cos(). (Thanks, Temani Afif!):

<code>@helps not (left: calc(1px * cos(45deg))) {
  time {
    left: 50% !necessary;
    high: 50% !necessary;
    rework: translate(-50%,-50%) rotate(var(--_d)) translate(var(--_r)) rotate(calc(-1*var(--_d)))
  }
}</code>

And, voilà! Our clock is completed! Right here’s the ultimate demo yet another time. Once more, it’s solely supported in Firefox and Safari in the meanwhile.

What else can we do?

Simply messing round right here, however we will shortly flip our clock right into a round picture gallery by changing the  tags with  then updating the width (--_w) and radius (--_r) values:

Let’s strive yet another. I discussed earlier how the clock appeared sort of like a contemporary artwork experiment. We will lean into that and re-create a sample I noticed on a poster (that I sadly didn’t purchase) in an artwork gallery the opposite day. As I recall, it was known as “Moon” and consisted of a bunch of dots forming a circle.

A large circle formed out of a bunch of smaller filled circles of various earthtone colors.

We’ll use an unordered checklist this time for the reason that circles don’t observe a specific order. We’re not even going to place all of the checklist gadgets within the markup. As an alternative, let’s inject them with JavaScript and add a couple of controls we will use to govern the ultimate outcome.

The controls are vary inputs () which we’ll wrap in a and hear for the enter occasion.

<code><kind id="controls">
  <fieldset>
    <label>Variety of rings
      <enter kind="vary" min="2" max="12" worth="10" id="rings" />
    </label>
    <label>Dots per ring
      <enter kind="vary" min="5" max="12" worth="7" id="dots" />
    </label>
    <label>Unfold
      <enter kind="vary" min="10" max="40" worth="40" id="unfold" />
    </label>
  </fieldset>
</kind></code>

We’ll run this methodology on “enter”, which is able to create a bunch of

  • parts with the diploma (--_d) variable we used earlier utilized to every one. We will additionally repurpose our radius variable (--_r) .

    I additionally need the dots to be completely different colours. So, let’s randomize (properly, not utterly randomized) the HSL coloration worth for every checklist merchandise and retailer it as a brand new CSS variable, --_bgc:

    <code>const replace = () => {
      let s = "";
      for (let i = 1; i <= rings.valueAsNumber; i++) {
        const r = unfold.valueAsNumber * i;
        const theta = coords(dots.valueAsNumber * i);
        for (let j = 0; j < theta.size; j++) {
          s += `<li model="--_d:${theta[j]};--_r:${r}px;--_bgc:hsl(${random(
            50,
            25
          )},${random(90, 50)}%,${random(90, 60)}%)"></li>`;
        }
      }
      app.innerHTML = s;
    }</code>

    The random() methodology picks a worth inside an outlined vary of numbers:

    <code>const random = (max, min = 0, f = true) => f ? Math.ground(Math.random() * (max - min) + min) : Math.random() * max;</code>

    And that’s it. We use JavaScript to render the markup, however as quickly because it’s rendered, we don’t actually need it. The sin() and cos() features assist us place all of the dots in the best spots.

    Ultimate ideas

    Inserting issues round a circle is a reasonably primary instance to display the powers of trigonometry features like sin() and cos(). However it’s actually cool that we’re getting fashionable CSS options that present new options for outdated workarounds I’m certain we’ll see far more attention-grabbing, advanced, and inventive use circumstances, particularly as browser assist involves Chrome and Edge.

  • Supply hyperlink

    Leave a Reply

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