Loading
Flexible Ribbon Banner with Tailwind CSS 10 exercises
solution

Meaningful Value Extraction

Simplifying the calculation

Since our container shape is a perfect square, we don’t need to do the complicated math above.

If we agree that each side (a and b) of the square has a length of 1, the square root of a square + b square becomes simpler.

1 square remains 1. So what we l

Loading solution

Transcript

0:00 We want to transform this arbitrary value here into a class called w-square-diagonal. Obviously, we broke the design since that doesn't exist yet, but let's work on that. Here's what we want the calculation to be doing.

0:14 If we agree that both the height and the width of the container is one, the value of the diagonal, which is the square root of A^2 + B^2, is also the square root of 1^2 + 1^2. 1^2 is 1, so that value here is, in fact, the square root of 2. While it's pretty tricky to calculate the square root of a number in CSS, it's really easy to do with JavaScript.

0:38 A good place to do this abstraction would be in a Tailwind config. Inside the config, I will extend the theme. We could consider extending the entire spacing object, but right now, this squared diagonal width we only want to set as a width.

0:52 I'll open the width object and create a new square-diagonal key, and here we'll do some maths with JavaScript. I can get the square root of 2 with math.sqrt and pass the number 2. With that, we've created a new w-square-diagonal utility class, but it looks kind of broken.

1:10 If we hover over that class to see what was generated, it generated a width of 1.41421356-blah-blah-blah pixels. We don't want pixels, and we don't want 1.41. We want 141. What we can do is multiply it by 100 and then convert this into a percentage value by adding a string of percent.

1:30 Now, the entire value will be coerced into a string. You can see that the width works perfectly now. If I hover over the class, we have that width set correctly. Arguably, there's a few too many decimals here. Let's stick to just two decimals.

1:45 To do so, we're going to take this math expression and run it through toFixed, which will let us define how many fraction digits we want. Here, we'll go with two. Now, we have this really tidy 141.42 percent set as the width of the w-square-diagonal utility class.

2:03 I think we solved a pretty tricky problem here, and we've solved it in a really elegant manner.