Archive

Archive for the ‘Designing’ Category

A CSS-Only Star Rating Component and More! (Part 2)

March 7th, 2025 No comments
Red circle representing the thumb element is at the far right of the container but not quite all the way there.

To rectify this we use the animation-range property to make the start of the animation when the subject has completely entered the scroller from the right (entry 100%) and the end of the animation when the subject starts to exit the scroller from the left (exit 0%).

Red circle representing the thumb element displayed qt the far right of the container where the animation starts.

To summarize, the thumb element will move within input’s area and that movement is used to control the progress of an animation that animates a variable between the input’s min and max attribute values. We have our replacement for document.querySelector("input").value in JavaScript!

What’s going on with all the --val instances everywhere? Is it the same thing each time?

I am deliberately using the same --val everywhere to confuse you a little and push you to try to understand what is going on. We usually use the dashed ident (--) notation to define custom properties (also called CSS variables) that we later call with var(). This is still true but that same notation can be used to name other things as well.

In our examples we have three different things named --val:

  1. The variable that is animated and registered using @property. It contains the selected value and is used to style the input.
  2. The named view timeline defined by view-timeline and used by animation-timeline.
  3. The keyframes named --val and called by animation.

Here is the same code written with different names for more clarity:

@property --val {
  syntax: "<number>";
  inherits: true;
  initial-value: 0; 
}

input[type="range"] {
  --min: attr(min type(<number>));
  --max: attr(max type(<number>));

  timeline-scope: --timeline;
  animation: value_update linear both;
  animation-timeline: --timeline;
  animation-range: entry 100% exit 0%;
  overflow: hidden;
}

@keyframes value_update {
  0%   { --val: var(--max) }
  100% { --val: var(--min) }
}

input[type="range"]::thumb {
  view-timeline: --timeine inline;
}

The star rating component

All that we have done up to now is get the selected value of the input range — which is honestly about 90% of the work we need to do. What remains is some basic styles and code taken from what we made in the first article.

If we omit the code from the previous section and the code from the previous article here is what we are left with:

input[type="range"] {
  background: 
    linear-gradient(90deg,
      hsl(calc(30 + 4 * var(--val)) 100% 56%) calc(var(--val) * 100% / var(--max)),
      #7b7b7b 0
    );
}
input[type="range"]::thumb {
  opacity: 0;
}

We make the thumb invisible and we define a gradient on the main element to color in the stars. No surprise here, but the gradient uses the same --val variable that contains the selected value to inform how much is colored in.

When, for example, you select three stars, the --val variable will equal 3 and the color stop of the first color will equal 3*100%/5 , or 60%, meaning three stars are colored in. That same color is also dynamic as I am using the hsl() function where the first argument (the hue) is a function of --val as well.

Here is the full demo, which you will want to open in Chrome 115+ at the time I’m writing this:

CodePen Embed Fallback

And guess what? This implementation works with half stars as well without the need to change the CSS. All you have to do is update the input’s attributes to work in half increments. Remember, we’re yanking these values out of HTML into CSS using attr(), which reads the attributes and returns them to us.

<input type="range" min=".5" step=".5" max="5">
CodePen Embed Fallback

That’s it! We have our rating star component that you can easily control by adjusting the attributes.

So, should I use border-image or a scroll-driven animation?

If we look past the browser support factor, I consider this version better than the border-image approach we used in the first article. The border-image version is simpler and does the job pretty well, but it’s limited in what it can do. While our goal is to create a star rating component, it’s good to be able to do more and be able to style an input range as you want.

With scroll-driven animations, we have more flexibility since the idea is to first get the value of the input and then use it to style the element. I know it’s not easy to grasp but don’t worry about that. You will face scroll-driven animations more often in the future and it will become more familiar with time. This example will look easy to you in good time.

Worth noting, that the code used to get the value is a generic code that you can easily reuse even if you are not going to style the input itself. Getting the value of the input is independent of styling it.

Here is a demo where I am adding

In the last article, we created a CSS-only star rating component using the CSS mask and border-image properties, as well as the newly enhanced attr() function. We ended with CSS code that we can easily adjust to create component variations, including a heart rating and volume control.

This second article will study a different approach that gives us more flexibility. Instead of the border-image trick we used in the first article, we will rely on scroll-driven animations!

Here is the same star rating component with the new implementation. And since we’re treading in experimental territory, you’ll want to view this in Chrome 115+ while we wait for Safari and Firefox support:

CodePen Embed Fallback

Do you spot the difference between this and the final demo in the first article? This time, I am updating the color of the stars based on how many of them are selected — something we cannot do using the border-image trick!

I highly recommend you read the first article before jumping into this second part if you missed it, as I will be referring to concepts and techniques that we explored over there.

One more time: At the time of writing, only Chrome 115+ and Edge 115+ fully support the features we will be using in this article, so please use either one of those as you follow along.

Why scroll-driven animations?

You might be wondering why we’re talking about scroll-driven animation when there’s nothing to scroll to in the star rating component. Scrolling? Animation? But we have nothing to scroll or animate! It’s even more confusing when you read the MDN explainer for scroll-driven animations:

It allows you to animate property values based on a progression along a scroll-based timeline instead of the default time-based document timeline. This means that you can animate an element by scrolling a scrollable element, rather than just by the passing of time.

But if you keep reading you will see that we have two types of scroll-based timelines: scroll progress timelines and view progress timelines. In our case, we are going to use the second one; a view progress timeline, and here is how MDN describes it:

You progress this timeline based on the change in visibility of an element (known as the subject) inside a scroller. The visibility of the subject inside the scroller is tracked as a percentage of progress — by default, the timeline is at 0% when the subject is first visible at one edge of the scroller, and 100% when it reaches the opposite edge.

You can check out the CSS-Tricks almanac definition for view-timeline-name while you’re at it for another explanation.

Things start to make more sense if we consider the thumb element as the subject and the input element as the scroller. After all, the thumb moves within the input area, so its visibility changes. We can track that movement as a percentage of progress and convert it to a value we can use to style the input element. We are essentially going to implement the equivalent of document.querySelector("input").value in JavaScript but with vanilla CSS!

The implementation

Now that we have an idea of how this works, let’s see how everything translates into code.

@property --val {
  syntax: "<number>";
  inherits: true;
  initial-value: 0; 
}

input[type="range"] {
  --min: attr(min type(<number>));
  --max: attr(max type(<number>));

  timeline-scope: --val;
  animation: --val linear both;
  animation-timeline: --val;
  animation-range: entry 100% exit 0%;
  overflow: hidden;
}

@keyframes --val {
  0%   { --val: var(--max) }
  100% { --val: var(--min) }
}

input[type="range"]::thumb {
  view-timeline: --val inline;
}

I know, this is a lot of strange syntax! But we will dissect each line and you will see that it’s not all that complex at the end of the day.

The subject and the scroller

We start by defining the subject, i.e. the thumb element, and for this we use the view-timeline shorthand property. From the MDN page, we can read:

The view-timeline CSS shorthand property is used to define a named view progress timeline, which is progressed through based on the change in visibility of an element (known as the subject) inside a scrollable element (scroller). view-timeline is set on the subject.

I think it’s self-explanatory. The view timeline name is --val and the axis is inline since we’re working along the horizontal x-axis.

Next, we define the scroller, i.e. the input element, and for this, we use overflow: hidden (or overflow: auto). This part is the easiest but also the one you will forget the most so let me insist on this: don’t forget to define overflow on the scroller!

I insist on this because your code will work fine without defining overflow, but the values won’t be good. The reason is that the scroller exists but will be defined by the browser (depending on your page structure and your CSS) and most of the time it’s not the one you want. So let me repeat it another time: remember the overflow property!

The animation

Next up, we create an animation that animates the --val variable between the input’s min and max values. Like we did in the first article, we are using the newly-enhanced attr() function to get those values. See that? The “animation” part of the scroll-driven animation, an animation we link to the view timeline we defined on the subject using animation-timeline. And to be able to animate a variable we register it using @property.

Note the use of timeline-scope which is another tricky feature that’s easy to overlook. By default, named view timelines are scoped to the element where they are defined and its descendant. In our case, the input is a parent element of the thumb so it cannot access the named view timeline. To overcome this, we increase the scope using timeline-scope. Again, from MDN:

timeline-scope is given the name of a timeline defined on a descendant element; this causes the scope of the timeline to be increased to the element that timeline-scope is set on and any of its descendants. In other words, that element and any of its descendant elements can now be controlled using that timeline.

Never forget about this! Sometimes everything is correctly defined but nothing is working because you forget about the scope.

There’s something else you might be wondering:

Why are the keyframes values inverted? Why is the min is set to 100% and the max set to 0%?

To understand this, let’s first take the following example where you can scroll the container horizontally to reveal a red circle inside of it.

CodePen Embed Fallback

Initially, the red circle is hidden on the right side. Once we start scrolling, it appears from the right side, then disappears to the left as you continue scrolling towards the right. We scroll from left to right but our actual movement is from right to left.

In our case, we don’t have any scrolling since our subject (the thumb) will not overflow the scroller (the input) but the main logic is the same. The starting point is the right side and the ending point is the left side. In other words, the animation starts when the thumb is on the right side (the input’s max value) and will end when it’s on the left side (the input’s min value).

The animation range

The last piece of the puzzle is the following important line of code:

animation-range: entry 100% exit 0%;

By default, the animation starts when the subject starts to enter the scroller from the right and ends when the subject has completely exited the scroller from the left. This is not good because, as we said, the thumb will not overflow the scroller, so it will never reach the start and the end of the animation.

To rectify this we use the animation-range property to make the start of the animation when the subject has completely entered the scroller from the right (entry 100%) and the end of the animation when the subject starts to exit the scroller from the left (exit 0%).

Red circle representing the thumb element displayed qt the far right of the container where the animation starts.

To summarize, the thumb element will move within input’s area and that movement is used to control the progress of an animation that animates a variable between the input’s min and max attribute values. We have our replacement for document.querySelector("input").value in JavaScript!

What’s going on with all the --val instances everywhere? Is it the same thing each time?

I am deliberately using the same --val everywhere to confuse you a little and push you to try to understand what is going on. We usually use the dashed ident (--) notation to define custom properties (also called CSS variables) that we later call with var(). This is still true but that same notation can be used to name other things as well.

In our examples we have three different things named --val:

  1. The variable that is animated and registered using @property. It contains the selected value and is used to style the input.
  2. The named view timeline defined by view-timeline and used by animation-timeline.
  3. The keyframes named --val and called by animation.

Here is the same code written with different names for more clarity:

@property --val {
  syntax: "<number>";
  inherits: true;
  initial-value: 0; 
}

input[type="range"] {
  --min: attr(min type(<number>));
  --max: attr(max type(<number>));

  timeline-scope: --timeline;
  animation: value_update linear both;
  animation-timeline: --timeline;
  animation-range: entry 100% exit 0%;
  overflow: hidden;
}

@keyframes value_update {
  0%   { --val: var(--max) }
  100% { --val: var(--min) }
}

input[type="range"]::thumb {
  view-timeline: --timeine inline;
}

The star rating component

All that we have done up to now is get the selected value of the input range — which is honestly about 90% of the work we need to do. What remains is some basic styles and code taken from what we made in the first article.

If we omit the code from the previous section and the code from the previous article here is what we are left with:

input[type="range"] {
  background: 
    linear-gradient(90deg,
      hsl(calc(30 + 4 * var(--val)) 100% 56%) calc(var(--val) * 100% / var(--max)),
      #7b7b7b 0
    );
}
input[type="range"]::thumb {
  opacity: 0;
}

We make the thumb invisible and we define a gradient on the main element to color in the stars. No surprise here, but the gradient uses the same --val variable that contains the selected value to inform how much is colored in.

When, for example, you select three stars, the --val variable will equal 3 and the color stop of the first color will equal 3*100%/5 , or 60%, meaning three stars are colored in. That same color is also dynamic as I am using the hsl() function where the first argument (the hue) is a function of --val as well.

Here is the full demo, which you will want to open in Chrome 115+ at the time I’m writing this:

CodePen Embed Fallback

And guess what? This implementation works with half stars as well without the need to change the CSS. All you have to do is update the input’s attributes to work in half increments. Remember, we’re yanking these values out of HTML into CSS using attr(), which reads the attributes and returns them to us.

<input type="range" min=".5" step=".5" max="5">
CodePen Embed Fallback

That’s it! We have our rating star component that you can easily control by adjusting the attributes.

So, should I use border-image or a scroll-driven animation?

If we look past the browser support factor, I consider this version better than the border-image approach we used in the first article. The border-image version is simpler and does the job pretty well, but it’s limited in what it can do. While our goal is to create a star rating component, it’s good to be able to do more and be able to style an input range as you want.

With scroll-driven animations, we have more flexibility since the idea is to first get the value of the input and then use it to style the element. I know it’s not easy to grasp but don’t worry about that. You will face scroll-driven animations more often in the future and it will become more familiar with time. This example will look easy to you in good time.

Worth noting, that the code used to get the value is a generic code that you can easily reuse even if you are not going to style the input itself. Getting the value of the input is independent of styling it.

Here is a demo where I am adding a tooltip to a range slider to show its value:

CodePen Embed Fallback

Many techniques are involved to create that demo and one of them is using scroll-driven animations to get the input value and show it inside the tooltip!

Here is another demo using the same technique where different range sliders are controlling different variables on the page.

CodePen Embed Fallback

And why not a wavy range slider?

CodePen Embed Fallback

This one is a bit crazy but it illustrates how far we go with styling an input range! So, even if your goal is not to create a star rating component, there are a lot of use cases where such a technique can be really useful.

Conclusion

I hope you enjoyed this brief two-part series. In addition to a star rating component made with minimal code, we have explored a lot of cool and modern features, including the attr() function, CSS mask, and scroll-driven animations. It’s still early to adopt all of these features in production because of browser support, but it’s a good time to explore them and see what can be done soon using only CSS.

Article series

  1. A CSS-Only Star Rating Component and More! (Part 1)
  2. A CSS-Only Star Rating Component and More! (Part 2)

A CSS-Only Star Rating Component and More! (Part 2) originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

Categories: Designing, Others Tags:

Blast from the Past: Grumpy Cat: From Viral Fame to Cultural Icon

March 7th, 2025 No comments

Grumpy Cat, famous for her permanent scowl, captured the internet’s heart with her relatable and sarcastic meme captions. Her rise to fame turned her into a beloved cultural symbol of frustration and humor that still resonates today.

Categories: Designing, Others Tags:

Digg.com is Back: The Reboot We Didn’t Know We Needed

March 5th, 2025 No comments

Digg is making a comeback under its original founder, Kevin Rose, and Reddit co-founder Alexis Ohanian, with a renewed focus on AI-driven content curation and community engagement.

Categories: Designing, Others Tags:

The Worst Branding Blunder: Meta’s Messenger Logo U-Turn

March 5th, 2025 No comments

Meta’s switch back to the blue Messenger logo has sparked confusion, reflecting the company’s ongoing identity crisis. Zuckerberg’s constant flip-flopping only adds to the uncertainty.

Categories: Designing, Others Tags:

Why Icon-Only Design Is Failing Users: The Case for Text Labels

March 3rd, 2025 No comments

Icons may look sleek, but they often create confusion and increase cognitive load, especially in complex applications. Text labels, on the other hand, provide clear, unambiguous communication, making them a far superior choice for usability and accessibility in design.

Categories: Designing, Others Tags:

A CSS-Only Star Rating Component and More! (Part 1)

February 28th, 2025 No comments
DevTools inspecting an input element, showing the shadow root element parts.

Creating a star rating component is a classic exercise in web development. It has been done and re-done many times using different techniques. We usually need a small amount of JavaScript to pull it together, but what about a CSS-only implementation? Yes, it is possible!

Here is a demo of a CSS-only star rating component. You can click to update the rating.

CodePen Embed Fallback

Cool, right? In addition to being CSS-only, the HTML code is nothing but a single element:

<input type="range" min="1" max="5">

An input range element is the perfect candidate here since it allows a user to select a numeric value between two boundaries (the min and max). Our goal is to style that native element and transform it into a star rating component without additional markup or any script! We will also create more components at the end, so follow along.

Note: This article will only focus on the CSS part. While I try my best to consider UI, UX, and accessibility aspects, my component is not perfect. It may have some drawbacks (bugs, accessibility issues, etc), so please use it with caution.

The element

You probably know it but styling native elements such as inputs is a bit tricky due to all the default browser styles and also the different internal structures. If, for example, you inspect the code of an input range you will see a different HTML between Chrome (or Safari, or Edge) and Firefox.

Luckily, we have some common parts that I will rely on. I will target two different elements: the main element (the input itself) and the thumb element (the one you slide with your mouse to update the value).

Our CSS will mainly look like this:

input[type="range"] {
  /* styling the main element */
}

input[type="range" i]::-webkit-slider-thumb {
  /* styling the thumb for Chrome, Safari and Edge */
}

input[type="range"]::-moz-range-thumb {
  /* styling the thumb for Firefox */
}

The only drawback is that we need to repeat the styles of the thumb element twice. Don’t try to do the following:

input[type="range" i]::-webkit-slider-thumb,
input[type="range"]::-moz-range-thumb {
  /* styling the thumb */
}

This doesn’t work because the whole selector is invalid. Chrome & Co. don’t understand the ::-moz-* part and Firefox doesn’t understand the ::-webkit-* part. For the sake of simplicity, I will use the following selector for this article:

input[type="range"]::thumb {
  /* styling the thumb */
}

But the demo contains the real selectors with the duplicated styles. Enough introduction, let’s start coding!

Styling the main element (the star shape)

We start by defining the size:

input[type="range"] {
  --s: 100px; /* control the size*/
  
  height: var(--s);
  aspect-ratio: 5;
  
  appearance: none; /* remove the default browser styles */
}

If we consider that each star is placed within a square area, then for a 5-star rating we need a width equal to five times the height, hence the use of aspect-ratio: 5.

CodePen Embed Fallback

That 5 value is also the value defined as the max attribute for the input element.

<input type="range" min="1" max="5">

So, we can rely on the newly enhanced attr() function (Chrome-only at the moment) to read that value instead of manually defining it!

input[type="range"] {
  --s: 100px; /* control the size*/
  
  height: var(--s);
  aspect-ratio: attr(max type(<number>));
  
  appearance: none; /* remove the default browser styles */
}

Now you can control the number of stars by simply adjusting the max attribute. This is great because the max attribute is also used by the browser internally, so updating that value will control our implementation as well as the browser’s behavior.

This enhanced version of attr() is only available in Chrome for now so all my demos will contain a fallback to help with unsupported browsers.

The next step is to use a CSS mask to create the stars. We need the shape to repeat five times (or more depending on the max value) so the mask size should be equal to var(--s) var(--s) or var(--s) 100% or simply var(--s) since by default the height will be equal to 100%.

input[type="range"] {  
  --s: 100px; /* control the size*/
  
  height: var(--s);
  aspect-ratio: attr(max type(<number>));
  
  appearance: none; /* remove the default browser styles */

  mask-image: /* ... */;
  mask-size: var(--s);
}

What about the mask-image property you might ask? I think it’s no surprise that I tell you it will require a few gradients, but it could also be SVG instead. This article is about creating a star-rating component but I would like to keep the star part kind of generic so you can easily replace it with any shape you want. That’s why I say “and more” in the title of this post. We will see later how using the same code structure we can get a variety of different variations.

Here is a demo showing two different implementations for the star. One is using gradients and the other is using an SVG.

CodePen Embed Fallback

In this case, the SVG implementation looks cleaner and the code is also shorter but keep both approaches in your back pocket because a gradient implementation can do a better job in some situations.

Styling the thumb (the selected value)

Let’s now focus on the thumb element. Take the last demo then click the stars and notice the position of the thumb.

CodePen Embed Fallback

The good thing is that the thumb is always within the area of a given star for all the values (from min to max), but the position is different for each star. It would be good if the position is always the same, regardless of the value. Ideally, the thumb should always be at the center of the stars for consistency.

Here is a figure to illustrate the position and how to update it.

The lines are the position of the thumb for each value. On the left, we have the default positions where the thumb goes from the left edge to the right edge of the main element. On the right, if we restrict the position of the thumb to a smaller area by adding some spaces on the sides, we get much better alignment. That space is equal to half the size of one star, or var(--s)/2. We can use padding for this:

input[type="range"] {  
  --s: 100px; /* control the size */
  
  height: var(--s);
  aspect-ratio: attr(max type(<number>));
  padding-inline: calc(var(--s) / 2);
  box-sizing: border-box;
  
  appearance: none; /* remove the default browser styles */

  mask-image: ...;
  mask-size: var(--s);
}
CodePen Embed Fallback

It’s better but not perfect because I am not accounting for the thumb size, which means we don’t have true centering. It’s not an issue because I will make the size of the thumb very small with a width equal to 1px.

input[type="range"]::thumb {
  width: 1px;
  height: var(--s);  

  appearance: none; /* remove the default browser styles */ 
}
CodePen Embed Fallback

The thumb is now a thin line placed at the center of the stars. I am using a red color to highlight the position but in reality, I don’t need any color because it will be transparent.

You may think we are still far from the final result but we are almost done! One property is missing to complete the puzzle: border-image.

The border-image property allows us to draw decorations outside an element thanks to its outset feature. For this reason, I made the thumb small and transparent. The coloration will be done using border-image. I will use a gradient with two solid colors as the source:

linear-gradient(90deg, gold 50%, grey 0);

And we write the following:

border-image: linear-gradient(90deg, gold 50%, grey 0) fill 0 // 0 100px;

The above means that we extend the area of the border-image from each side of the element by 100px and the gradient will fill that area. In other words, each color of the gradient will cover half of that area, which is 100px.

CodePen Embed Fallback

Do you see the logic? We created a kind of overflowing coloration on each side of the thumb — a coloration that will logically follow the thumb so each time you click a star it slides into place!

Now instead of 100px let’s use a very big value:

CodePen Embed Fallback

We are getting close! The coloration is filling all the stars but we don’t want it to be in the middle but rather across the entire selected star. For this, we update the gradient a bit and instead of using 50%, we use 50% + var(--s)/2. We add an offset equal to half the width of a star which means the first color will take more space and our star rating component is perfect!

CodePen Embed Fallback

We can still optimize the code a little where instead of defining a height for the thumb, we keep it 0 and we consider the vertical outset of border-image to spread the coloration.

input[type="range"]::thumb{
  width: 1px;
  border-image: 
    linear-gradient(90deg, gold calc(50% + var(--s) / 2), grey 0)
    fill 0 // var(--s) 500px;
  appearance: none;
}

We can also write the gradient differently using a conic gradient instead:

input[type="range"]::thumb{
  width: 1px;
  border-image: 
    conic-gradient(at calc(50% + var(--s) / 2), grey 50%, gold 0)
    fill 0 // var(--s) 500px;
  appearance: none;
}

I know that the syntax of border-image is not easy to grasp and I went a bit fast with the explanation. But I have a very detailed article over at Smashing Magazine where I dissect that property with a lot of examples that I invite you to read for a deeper dive into how the property works.

The full code of our component is this:

<input type="range" min="1" max="5">
input[type="range"] {  
  --s: 100px; /* control the size*/
  
  height: var(--s);
  aspect-ratio: attr(max type(<number>));
  padding-inline: calc(var(--s) / 2); 
  box-sizing: border-box; 
  appearance: none; 
  mask-image: /* ... */; /* either an SVG or gradients */
  mask-size: var(--s);
}

input[type="range"]::thumb {
  width: 1px;
  border-image: 
    conic-gradient(at calc(50% + var(--s) / 2), grey 50%, gold 0)
    fill 0//var(--s) 500px;
  appearance: none;
}

That’s all! A few lines of CSS code and we have a nice rating star component!

Half-Star Rating

What about having a granularity of half a star as a rating? It’s something common and we can do it with the previous code by making a few adjustments.

First, we update the input element to increment in half steps instead of full steps:

<input type="range" min=".5" step=".5" max="5">

By default, the step is equal to 1 but we can update it to .5 (or any value) then we update the min value to .5 as well. On the CSS side, we change the padding from var(--s)/2 to var(--s)/4, and we do the same for the offset inside the gradient.

input[type="range"] {  
  --s: 100px; /* control the size*/
  
  height: var(--s);
  aspect-ratio: attr(max type(<number>));
  padding-inline: calc(var(--s) / 4); 
  box-sizing: border-box; 
  appearance: none; 
  mask-image: ...; /* either SVG or gradients */
  mask-size: var(--s);
}

input[type="range"]::thumb{
  width: 1px;
  border-image: 
    conic-gradient(at calc(50% + var(--s) / 4),grey 50%, gold 0)
    fill 0 // var(--s) 500px;
  appearance: none;
}

The difference between the two implementations is a factor of one-half which is also the step value. That means we can use attr() and create a generic code that works for both cases.

input[type="range"] {  
  --s: 100px; /* control the size*/
  
  --_s: calc(attr(step type(<number>),1) * var(--s) / 2);
  height: var(--s);
  aspect-ratio: attr(max type(<number>));
  padding-inline: var(--_s);
  box-sizing: border-box; 
  appearance: none; 
  mask-image: ...; /* either an SVG or gradients */
  mask-size: var(--s);
}

input[type="range"]::thumb{
  width: 1px;
  border-image: 
    conic-gradient(at calc(50% + var(--_s)),gold 50%,grey 0)
    fill 0//var(--s) 500px;
  appearance: none;
}

Here is a demo where modifying the step is all that you need to do to control the granularity. Don’t forget that you can also control the number of stars using the max attribute.

CodePen Embed Fallback

Using the keyboard to adjust the rating

As you may know, we can adjust the value of an input range slider using a keyboard, so we can control the rating using the keyboard as well. That’s a good thing but there is a caveat. Due to the use of the mask property, we no longer have the default outline that indicates keyboard focus which is an accessibility concern for those who rely on keyboard input.

For a better user experience and to make the component more accessible, it’s good to display an outline on focus. The easiest solution is to add an extra wrapper:

<span>
  <input type="range" min="1" max="5">
</span>

That will have an outline when the input inside has focus:

span:has(:focus-visible) {
  outline: 2px solid;
}

Try to use your keyboard in the below example to adjust both ratings:

CodePen Embed Fallback

Another idea is to consider a more complex mask configuration that prevents hiding the outline (or any outside decoration). The trick is to start with the following:

mask:
  conic-gradient(#000 0 0) exclude,
  conic-gradient(#000 0 0) no-clip;

The no-clip keyword means that nothing from the element will be clipped (including outlines). Then we use an exclude composition with another gradient. The exclusion will hide everything inside the element while keeping what is outside visible.

Finally, we add back the mask that creates the star shapes:

mask: 
  /* ... */ 0/var(--s), 
  conic-gradient(#000 0 0) exclude,
  conic-gradient(#000 0 0) no-clip;

I prefer using this last method because it maintains the single-element implementation but maybe your HTML structure allows you to add focus on an upper element and you can keep the mask configuration simple. It totally depends!

CodePen Embed Fallback

Credits to Ana Tudor for the last trick!

More examples!

As I said earlier, what we are making is more than a star rating component. You can easily update the mask value to use any shape you want.

Here is an example where I am using an SVG of a heart instead of a star.

CodePen Embed Fallback

Why not butterflies?

CodePen Embed Fallback

This time I am using a PNG image as a mask. If you are not comfortable using SVG or gradients you can use a transparent image instead. As long as you have an SVG, a PNG, or gradients, there is no limit on what you can do with this as far as shapes go.

We can go even further into the customization and create a volume control component like below:

CodePen Embed Fallback

I am not repeating a specific shape in that last example, but am using a complex mask configuration to create a signal shape.

Conclusion

We started with a star rating component and ended with a bunch of cool examples. The title could have been “How to style an input range element” because this is what we did. We upgraded a native component without any script or extra markup, and with only a few lines of CSS.

What about you? Can you think about another fancy component using the same code structure? Share your example in the comment section!

Article series

  1. A CSS-Only Star Rating Component and More! (Part 1)
  2. A CSS-Only Star Rating Component and More! (Part 2) — Coming March 7!

A CSS-Only Star Rating Component and More! (Part 1) originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

Categories: Designing, Others Tags:

Compilation: 15 Hilarious Google Flops

February 28th, 2025 No comments

Even tech giants like Google stumble, with flops like Google+ and Google Glass proving that not every idea sticks. Often caused by overestimating demand or poor execution, these failures show that even the boldest innovators sometimes miss the mark.

Categories: Designing, Others Tags:

Goodbye, Blue Links—Hello, Rainbow Revolution!

February 26th, 2025 No comments

The classic blue hyperlink is fading as designers adopt colorful, creative alternatives. While stylish, these modern links can sometimes confuse users, leaving many nostalgic for the simplicity of the original blue.

Categories: Designing, Others Tags:

The Figma Dilemma: Too Many Cooks, Too Few Decisions

February 24th, 2025 No comments

Collaboration tools like Figma promise streamlined workflows and collective creativity, but there’s a darker side: too many opinions, endless edits, and a loss of individual vision. In this piece, we explore whether Figma’s collaborative power might actually hinder great design by inviting too many cooks into the kitchen.

Categories: Designing, Others Tags:

Applying the Web Dev Mindset to Dealing With Life Challenges

February 24th, 2025 No comments

Editor’s note: This article is outside the typical range of topics we normally cover around here and touches on sensitive topics including recollections from an abusive marriage. It doesn’t delve into much detail about the abuse and ends on a positive note. Thanks to Lee for sharing his take on the intersection between life and web development and for allowing us to gain professional insights from his personal life.

When my dad was alive, he used to say that work and home life should exist in separate “watertight compartments.” I shouldn’t bring work home or my home life to work. There’s the quote misattributed to Mark Twain about a dad seeming to magically grow from a fool to a wise man in the few years it took the son to grow from a teen to an adult — but in my case, the older I get, the more I question my dad’s advice.

It’s easy to romanticize someone in death — but when my dad wasn’t busy yelling, gambling the rent money, or disappearing to another state, his presence was like an AI simulating a father, throwing around words that sounded like a thing to say from a dad, but not helpful if you stopped to think about his statements for more than a minute.

Let’s state the obvious: you shouldn’t do your personal life at work or work too much overtime when your family needs you. But you don’t need the watertight compartments metaphor to understand that. The way he said it hinted at something more complicated and awful — it was as though he wanted me to have a split personality. I shouldn’t be a developer at home, especially around him because he couldn’t relate, since I got my programming genes from my mum. And he didn’t think I should pour too much of myself into my dev work. The grain of truth was that even if you love your job, it can’t love you back. Yet what I’m hooked on isn’t one job, but the power of code and language.

The lonely coder seems to free his mind at night

Maybe my dad’s platitudinous advice to maintain a distance between my identity and my work would be practicable to a bricklayer or a president — but it’s poorly suited to someone whose brain is wired for web development. The job is so multidisciplinary it defies being put in a box you can leave at the office. That puzzle at work only makes sense because of a comment the person you love said before bedtime about the usability of that mobile game they play. It turns out the app is a competitor to the next company you join, as though the narrator of your life planted the earlier scene like a Chekov’s gun plot point, the relevance of which is revealed when you have that “a-ha” moment at work.

Meanwhile, existence is so online that as you try to unwind, you can’t unsee the matrix you helped create, even when it’s well past 5 p.m. The user interface you are building wants you to be a psychologist, an artist, and a scientist. It demands the best of every part of you. The answer about implementing a complex user flow elegantly may only come to you in a dream.

Don’t feel too bad if it’s the wrong answer. Douglas Crockford believes it’s a miracle we can code at all. He postulates that the mystery of how the human brain can program when he sees no evolutionary basis is why we haven’t hit the singularity. If we understood how our brains create software, we could build an AI that can program well enough to make a program better than itself. It could do that recursively till we have an AI smarter than us.

And yet so far the best we have is the likes of the aptly named Github Copilot. The branding captures that we haven’t hit the singularity so much as a duality, in which humanity hopefully harmonizes with what Noam Chomsky calls a “kind of super-autocomplete,” the same way autotune used right can make a good singer sound better, or it can make us all sound like the same robot. We can barely get our code working even now that we have all evolved into AI-augmented cyborgs, but we also can’t seem to switch off our dev mindset at will.

My dev brain has no “off” switch — is that a bug or a feature?

What if the ability to program represents a different category of intelligence than we can measure with IQ tests, similar to neurodivergence, which carries unique strengths and weaknesses? I once read a study in which the researchers devised a test that appeared to accurately predict which first-year computer science students would be able to learn to program. They concluded that an aptitude for programming correlates with a “comfort with meaninglessness.” The researchers said that to write a program you have to “accept that whatever you might want the program to mean, the machine will blindly follow its meaningless rules and come to some meaningless conclusion. In the test, the consistent group showed a pre-acceptance of this fact.”

The realization is dangerous, as both George Orwell and Philip K. Dick warned us. If you can control what words mean, you can control people and not just machines. If you have been swiping on Tinder and take a moment to sit with the feelings you associate with the phrases “swipe right” and “swipe left,” you find your emotional responses reveal that the app’s visual language has taught you what is good and what is bad. This recalls the scene in “Through the Looking-Glass,” in which Humpty Dumpty tells Alice that words mean what he wants them to mean. Humpty’s not the nicest dude. The Alice books can be interpreted as Dodgson’s critique of the Victorian education system which the author thought robbed children of their imagination, and Humpty makes his comments about language in a “scornful tone,” as though Alice should not only accept what he says, but she should know it without being told. To use a term that itself means different things to different people, Humpty is gaslighting Alice. At least he’s more transparent about it than modern gaslighters, and there’s a funny xkcd in which Alice uses Humpty’s logic against him to take all his possessions.

Perhaps the ability to shape reality by modifying the consensus on what words mean isn’t inherently good or bad, but in itself “meaningless,” just something that is true. It’s probably not a coincidence the person who coined the phrases “the map is not the territory” and “the word is not the thing” was an engineer. What we do with this knowledge depends on our moral compass, much like someone with a penchant for cutting people up could choose to be a surgeon or a serial killer.

Toxic humans are like blackhat hackers

For around seven years, I was with a person who was psychologically and physically abusive. Abuse boils down to violating boundaries to gain control. As awful as that was, I do not think the person was irrational. There is a natural appeal for human beings pushing boundaries to get what they want. Kids do that naturally, for example, and pushing boundaries by making CSS do things it doesn’t want to is the premise of my articles on CSS-Tricks. I try to create something positive with my impulse to exploit the rules, which I hope makes the world slightly more illuminated. However, to understand those who would do us harm, we must first accept that their core motivation meets a relatable human need, albeit in unacceptable ways.

For instance, more than a decade ago, the former hosting provider for CSS-Tricks was hacked. Chris Coyier received a reactivation notice for his domain name indicating the primary email for his account had changed to someone else’s email address. After this was resolved and the smoke cleared, Chris interviewed the hacker to understand how social engineering was used for the attack — but he also wanted to understand the hacker’s motivations. “Earl Drudge” (ananagram for “drug dealer”) explained that it was nothing personal that led him to target Chris — but Earl does things for“money and attention” and Chris reflected that “as different as the ways that we choose to spend our time are I do things for money and attention also, which makes us not entirely different at our core.”

It reminds me of the trope that cops and criminals share many personality traits. Everyone who works in technology shares the mindset that allows me to bend the meaning and assumptions within technology to my will, which is why the qualifiers of blackhat and whitehat exist. They are two sides of the same coin. However, the utility of applying the rule-bending mindset to life itself has been recognized in the popularization of the term “life hack.” Hopefully, we are whitehat life hackers. A life hack is like discovering emergent gameplay that is a logical if unexpected consequence of what occurs in nature. It’s a conscious form of human evolution.

If you’ve worked on a popular website, you will find a surprisingly high percentage of people follow the rules as long as you explain properly. Then again a large percentage will ignore the rules out of laziness or ignorance rather than malice. Then there are hackers and developers, who want to understand how the rules can be used to our advantage, or we are just curious what happens when we don’t follow the rules. When my seven-year-old does his online math, he sometimes deliberately enters the wrong answer, to see what animation triggers. This is a benign form of the hacker mentality — but now it’s time to talk about my experience with a lifehacker of the blackhat variety, who liked experimenting with my deepest insecurities because exploiting them served her purpose.

Verbal abuse is like a cross-site scripting attack

William Faulkner wrote that “the past is never dead. It’s not even past.” Although I now share my life with a person who is kind, supportive, and fascinating, I’m arguably still trapped in the previous, abusive relationship, because I have children with that person. Sometimes you can’t control who you receive input from, but recognizing the potential for that input to be malicious and then taking control of how it is interpreted is how we defend against both cross-site scriptingand verbal abuse.

For example, my ex would input the word “stupid” and plenty of other names I can’t share on this blog. She would scream this into my consciousness again and again. It is just a word, like a malicious piece of JavaScript a user might save into your website. It’s a set of characters with no inherent meaning. The way you allow it to be interpreted does the damage. When the “stupid” script ran in my brain, it was laden with meanings and assumptions in the way I interpreted it, like a keyword in a high-level language that has been designed to represent a set of lower-level instructions:

  1. Intelligence was conflated with my self-worth.
  2. I believed she would not say the hurtful things after her tearful promises not to say them again once she was aware it hurt me, as though she was not aware the first time.
  3. I felt trapped being called names because I believed the relationship was something I needed.
  4. I believed the input at face value that my actual intelligence was the issue, rather than the power my ex gained over me by generating the reaction she wanted from me by her saying one magic word.

Patching the vulnerabilities in your psyche

My psychologist pointed out that the ex likely knew I was not stupid but the intent was to damage my self-worth to make me easy to control. To acknowledge my strengths would not achieve that. I also think my brand of intelligence isn’t the type she values. For instance, the strengths that make me capable of being a software engineer are invisible to my abuser. Ultimately it’s irrelevant whether she believed what she was shouting — because the purpose was the effect her words had, rather than their surface-level meaning. The vulnerability she exploited was that I treated her input as a first-class citizen, able to execute with the same privileges I had given to the scripts I had written for myself. Once I sanitized that input using therapy and self-hypnosis, I stopped allowing her malicious scripts to have the same importance as the scripts I had written for myself, because she didn’t deserve that privilege. The untruths about myself have lost their power — I can still review them like an inert block of JavaScript but they can’t hijack my self-worth.

Like Alice using Humpty Dumpty’s logic against him in the xkcd cartoon, I showed that if words inherently have no meaning, there is no reason I can’t reengineer myself so that my meanings for the words trump how the abuser wanted me to use them to hurt myself and make me question my reality. The sanitized version of the “stupid” script rewrites those statements to:

  1. I want to hurt you.
  2. I want to get what I want from you.
  3. I want to lower your self-worth so you will believe I am better than you so you won’t leave.

When you translate it like that, it has nothing to do with actual intelligence, and I’m secure enough to jokingly call myself an idiot in my previous article. It’s not that I’m colluding with the ghost of my ex in putting myself down. Rather, it’s a way of permitting myself not to be perfect because somewhere in human fallibility lies our ability to achieve what a computer can’t. I once worked with a manager who when I had a bug would say, “That’s good, at least you know you’re not a robot.” Being an idiot makes what I’ve achieved with CSS seem more beautiful because I work around not just the limitations in technology, but also my limitations. Some people won’t like it, or won’t get it. I have made peace with that.

We never expose ourselves to needless risk, but we must stay in our lane, assuming malicious input will keep trying to find its way in. The motive for that input is the malicious user’s journey, not ours. We limit the attack surface and spend our energy understanding how to protect ourselves rather than dwelling on how malicious people shouldn’t attempt what they will attempt.

Trauma and selection processes

In my new relationship, there was a stage in which my partner said that dating me was starting to feel like “a job interview that never ends” because I would endlessly vet her to avoid choosing someone who would hurt me again. The job interview analogy was sadly apt. I’ve had interviews in which the process maps out the scars from how the organization has previously inadvertently allowed negative forces to enter. The horror trope in which evil has to be invited reflects the truth that we unknowingly open our door to mistreatment and negativity.

My musings are not to be confused with victim blaming, but abusers can only abuse the power we give them. Therefore at some point, an interviewer may ask a question about what you would do with the power they are mulling handing you —and a web developer requires a lot of trust from a company. The interviewer will explain: “I ask because we’ve seen people do [X].” You can bet they are thinking of a specific person who did damage in the past. That knowledge might help you not to take the grilling personally. They probably didn’t give four interviews and an elaborate React coding challenge to the first few developers that helped get their company off the ground. However, at a different level of maturity, an organization or a person will evolve in what they need from a new person. We can’t hold that against them. Similar to a startup that only exists based on a bunch of ill-considered high-risk decisions, my relationship with my kids is more treasured than anything I own, and yet it all came from the worst mistake I ever made. My driver’s license said I was 30 but emotionally, I was unqualified to make the right decision for my future self, much like if you review your code from a year ago, it’s a good sign if you question what kind of idiot wrote it.

As determined as I was not to repeat that kind of mistake, my partner’s point about seeming to perpetually interview her was this: no matter how much older and wiser we think we are, letting a new person into our lives is ultimately always a leap of faith, on both sides of the equation.

Taking a planned plunge

Releasing a website into the wild represents another kind of leap of faith — but if you imagine an air-gapped machine with the best website in the world sitting on it where no human can access it, that has less value than the most primitive contact form that delivers value to a handful of users. My gambling dad may have put his appetite for risk to poor use. But it’s important to take calculated risks and trust that we can establish boundaries to limit the damage a bad actor can do, rather than kid ourselves that it’s possible to preempt risk entirely.

Hard things, you either survive them or you don’t. Getting security wrong can pose an existential threat to a company while compromising on psychological safety can pose an existential threat to a person. Yet there’s a reason “being vulnerable” is a positive phrase. When we create public-facing websites, it’s our job to balance the paradox of opening ourselves up to the world while doing everything to mitigate the risks. I decided to risk being vulnerable with you today because I hope it might help you see dev and life differently. So, I put aside the CodePens to get a little more personal, and if I’m right that front-end coding needs every part of your psyche to succeed, I hope you will permit dev to change your life, and your life experiences to change the way you do dev. I have faith that you’ll create something positive in both realms.


Applying the Web Dev Mindset to Dealing With Life Challenges originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

Categories: Designing, Others Tags: