Tired of Messy Code? Master the Art of Writing Clean Codebases

Category Image 073

You've conquered the initial hurdle, learning to code and landing your dream job. But the journey doesn't end there. Now comes the real challenge: writing good code. This isn't just about functionality; it's about crafting elegant, maintainable code that stands the test of time.

Navigating a poorly designed system feels like being lost in a foreign city with no map. These systems are often clunky, inefficient, and frustrating.

Chris’ Corner: Fresh Type

Typography Definitions Cover

I like the feeling of a good fresh typeface. Like design itself, type design has trends, and without being able to articulate it particularly well, I feel like I can feel a fresh type look from a stale one. That’s probably the thinking of an amateur, and I’m sure the world’s fanciest designers probably used one typeface their entire career and would scold my fickle soul. But also whatever. I’m cool with being the ever-changing Pepsi logo to the never-changing Coca-Cola logo.

Saikrishna Vanneldas did a good job of rounding up some newer fonts in the article Bored with Poppins & Inter, Here are Some New fresh Sans-Serif For 2023. They are all free / open-source, so that’s nice, not that I don’t think we all should be paying for type (we should, just not all situations call for that).

Jakarata Sans on Google Fonts
Manrope on Google Fonts

You know how a “viewport unit” in CSS (e.g. vw, dvh, vmax, etc) essentially boil down to “1% of the browser window” in the given direction? Well hopefully you know that we also have container units now (supported across the board) which are very similar but “1% of the nearest container” in the given direction.

If you’ve been interested in implementing the idea of fluid type over the years, you know that a lot of it is done with viewport units and clamp() to achieve fluid type sizing across different size screens while capping the min and max sizes against extremes.

It’s worth thinking about making container units a part of this story. It’s pretty clear to most that container queries are the best way to style an element based on its size. But that doesn’t help as directly with things like sizing type. Container units certainly do.

It might be as simple as something like this:

.card {
  container: card / inline-size;
  ...

  h2 {
    font-size: clamp(1.4rem, 1rem + 5cqi, 4rem);
  }
}
Example Pen

I’m using cqi here which you can think of like “container units in the inline direction” and I think it’ll be a commonly used container unit.

Stephanie Eckles has the best deep dive article on this in Container Query Units and Fluid Typography. Stephanie covers setting up a proper system for all this with fallbacks and such.


Say you were going to publish a book online as a web page. A book, implying a whole lot of text. Call it 100,000 words. You need to think about the experience of that. Are there chapters of decently small length such that each of them could be almost like a blog post with an individual URL and you can proceed through them in a linked manner? Would you make the entire thing one massive single HTML page that you just scroll through? Maybe go old-school cool and use a library like Turn.js to make epic skeuomorphic page turns??

(Naturally, there are a bunch of cool examples of page turning on CodePen.)

There is no one right answer, but I have seen some good examples recently:

  1. Robin Sloan’s e-book template Perfect Edition uses horizontal scroll-snapping to create a book reading experience that is how most modern e-book readers look/work to me.
  2. Mat Marquis’ JavaScript for Web Designers by A Book Apart is published online for free and has an extremely classy paginated-blog-posts look.
  3. Jeremy Keith’s Resilient Web Design works offline (assuming you’ve been there once), which is a nice touch.
Perfect Edition

Elliot Jay Stocks has a new podcast called Hello, type friends! which is an easy subscribe for me. Elliot says they won’t get into visual nuance of typography on the show, because audio would suck for that, but everyone involved will be type people so sounds fun to me. I enjoyed the first one with Jessica Hische.


There is this thing called Emoji Kitchen which allows you to combine emoji together:

But in order to use it, it’s baked into Gboard, a keyboard replacement thingy with all sorts of random features (works on Android and iOS though which is cool). They do now have a page that lets you browser the combinations right from the web.

The UI was a smidge confusing to me at first. You pick one from the top, then that middle panel just shows you the combinations it can make. You don’t get to pick any two random emojis and see what happens. Still super cool.

What’s funny, though, is even though Emoji Kitchen is only a year old and they don’t really say how it works, don’t you kinda just assume it’s AI-powered? If they did these by hand, I bet they probably wouldn’t now, just a year later. Facebook is making stickers with AI which isn’t terribly different than this really, except for, ya know, it’s totally un-curated and can make questionable stuff.


Random periodic reminder that variable fonts are awesome, this time from Jason Pamental who has been tooting that horn for a lot of years. Fixel is an awfully nice new one. If by some chance you’re using a variable font, but find the file size a little worrying, know that there is an app to remove the axes you aren’t using which can have pretty big savings.

How to Animate Gradient Text Using CSS

Category Image 036

Web design takes a captivating turn when CSS comes into play. It enables a world of transformations, such as taking static text elements and infusing them with life. Our focus today is one such engaging transformation – animate gradient text using CSS.

So, let’s demonstrate how a seemingly complex effect can be achieved with a few lines of code.

UNLIMITED DOWNLOADS: 400,000+ Fonts & Design Assets

Starting at only $16.50 per month!

Setting Up the Text in the HTML

We begin by defining our text element in HTML, which in this case is a simple heading:

<h1 class="animated-gradient">1stWebDesigner</h1>

Here, we create an <h1> element with a class called “animated-gradient”. This class becomes our anchor for creating the gradient animation in CSS.

Unfolding the Gradient Animation

The core part lies within our CSS. Let’s define the gradient and set it in motion with the following code:

/* Google Fonts for Open Sans */
@import url('https://fonts.googleapis.com/css2?family=Open+Sans:wght@700&amp;display=swap');

/* Define animation */
@keyframes gradient-shift {
  0% {background-position: 0%}
  100% {background-position: 100%}
}

/* Styling our animated gradient text */
.animated-gradient {
  font-family: 'Open Sans', sans-serif;
  font-size: 2em;
  background: linear-gradient(270deg, #ff4b59, #ff9057, #ffc764, #50e3c2, #4a90e2, #b8e986, #ff4b59);
  background-size: 200%;
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  animation: gradient-shift 3s ease-in-out infinite;
}

Our CSS setup does the following:

  • @import url: This directive fetches the Open Sans font from Google Fonts, noted for its modern and clean aesthetics.
  • @keyframes: Here, we define an animation named gradient-shift. This animation creates the illusion of motion in the gradient by shifting the background’s position from 0% to 100%.
  • font-family and font-size: These properties set our text’s font to Open Sans and its size to 2em.
  • background: This property generates a linear gradient using a striking array of colors. The gradient direction is set to 270 degrees, providing a left-to-right color flow.
  • background-size: This property, set to 200%, enlarges the background, contributing to the illusion of movement.
  • -webkit-background-clip and -webkit-text-fill-color: These properties render the text transparent, allowing the animated gradient to shine through.
  • animation: Lastly, we deploy our gradient-shift animation. It uses an ease-in-out timing function for smooth transitions and loops indefinitely, creating an ever-changing cascade of colors.

The Result

And there we have it! Check out the vibrant, animated gradient text:

See the Pen Animated Gradient Text by 1stWebDesigner (@firstwebdesigner) on CodePen.

Final Thoughts

The process of creating the animated gradient text effect is surprisingly straightforward, but the creative opportunities it unveils are far-reaching. With this foundational knowledge, you can experiment with different color schemes and gradient directions, apply the animation to various elements like buttons or headers, and even incorporate subtle animated accents into your design.

Remember, the real beauty of CSS is in its flexibility and power – it provides a vast canvas for creativity. You could also explore further with CSS keyframes to manipulate other properties and add more dynamic animations to your design. Feel free to dive deeper into the world of CSS animations with our guide on CSS keyframes.

How to Select and Use Nested Blocks in WordPress

Typography Definitions Cover

Do you want to learn how to select and use nested blocks in WordPress?

The WordPress Gutenberg nested blocks feature allows you to add multiple blocks within a parent block. Then, you can customize different block elements at the same time, organize post content efficiently, and access more design flexibility.

In this article, we will show you how to easily select and use WordPress nested blocks.

Select and use nested blocks in WordPress

What Are WordPress Nested Blocks?

The WordPress Gutenberg nested block feature allows you to insert (or ‘nest’) one or more blocks within another block.

Nested blocks help you create more complex layouts on your WordPress website by adding multiple blocks inside each other. This allows for more flexibility when designing and formatting content for pages and posts.

For instance, you can nest multiple Image blocks within a Group block to display a set of photos from a particular event or a series of artworks created using a particular technique.

Preview of WordPress nested blocks

Moreover, the nested block feature allows you to edit individual blocks separately. This means that you can customize each block according to your needs without affecting the other blocks. In turn, this results in better content organization, makes your content more attractive, and streamlines your content creation process.

That being said, let’s see how you can easily select and use WordPress Gutenberg nested blocks.

How to Use WordPress Nested Blocks

You can easily nest multiple blocks together using the Group or Columns block in the Gutenberg block editor.

First, you need to open up an existing or new post in the block editor from the WordPress admin sidebar.

From here, simply click on the ‘+’ button in the top left corner of the screen and find the ‘Group’ block. Upon clicking it and adding it to the page, you will need to select a layout for the blocks that you will nest together.

For this tutorial, we will be selecting the ‘Group’ layout.

Select Group block from the block menu

Next, simply click on the ‘+’ button on the screen to start adding content within the parent block.

For the sake of this tutorial, we will be adding an Image block.

Add an image block within the Group block

Upon adding the Image block, just click the ‘Group’ button in the block toolbar at the top to select the parent block.

Next, you need to click the ‘+’ button to open up the block menu, from where you can choose other blocks to add.

Open the block menu to add another block within the Group block

How to Configure WordPress Nested Block Settings

Once you have nested multiple blocks, you can configure their individual settings by clicking on each block. This will open up the block settings in the right column on the screen.

From here, you can adjust the background color, text color, and size of the individual blocks without affecting the other blocks that are nested within it.

Configure the individual block settings

To configure the settings of all the nested blocks together, you will have to click the ‘Group’ button in the block toolbar at the top. This will open up the parent block settings in the right column.

You can now configure the justification, orientation, background color, text color, and typography of all the nested blocks.

Keep in mind that these settings will affect all the blocks nested within the parent block.

Configure the settings of the Group block

You can also convert an existing individual block into nested blocks by clicking the ‘Options’ button in the top toolbar of any block.

This will open up a menu prompt, where you need to select the ‘Create Reusable block’ option.

Choose the Create Reusable Block option

Once you have done that, a new reusable block will be created where you can add multiple blocks.

After you are done, don’t forget to click the ‘Publish’ or ‘Update’ button to save your changes.

Create nested blocks

In our example, we have nested a Title, Image, and Paragraph block within a Group block. This is how the nested blocks looked on our demo website.

Preview of WordPress nested blocks

Bonus: Use the Wayfinder Plugin to Easily Select Nested Blocks

Sometimes, it can be difficult to select an individual block and configure it when there are multiple blocks nested together.

Luckily, the Wayfinder plugin makes it super easy to select nested blocks from a parent block and even tells you the type and class of the blocks.

First, you will need to install and activate the Wayfinder plugin. For more instructions, you may want to see our guide on how to install a WordPress plugin.

Upon activation, head over to the Settings » Wayfinder page from the WordPress admin sidebar.

Once you are there, all the settings will already be activated. You simply need to uncheck the box next to the settings that you don’t want to use.

For example, if you want Wayfinder to display block types for all the blocks in the editor, then keep the box checked next to the ‘Display block type’ option.

Configure the Wayfinder plugin settings

However, if you don’t want the plugin to display block classes, simply uncheck the box next to that option.

After configuring the settings, don’t forget to click the ‘Save Changes’ button.

Next, you need to open up an existing or new post from the WordPress admin sidebar.

Once you are there, hovering your mouse over any block will show an outline with its name. You will also be able to see the outline and name of any nested blocks within the parent block.

GIF for the Wayfinder plugin

This will help you identify all the different blocks that are nested within a Group or Columns block.

From here, you can easily select an individual block from the parent block to configure its settings.

Use Wayfinder plugin to easily select a block

You can also select all the nested blocks at the same time by simply clicking on the ‘Columns’ or ‘Group’ heading. This will open up the parent block settings in the right column.

Once you have configured the block settings, simply click the ‘Update’ or ‘Publish’ button to save your changes.

Click the Group block outline to open its settings

We hope this article helped you learn how to select and use WordPress nested blocks. You may also want to see our tutorial on how to change block height and width in WordPress and our top picks for the must-have WordPress plugins to help grow your site.

If you liked this article, then please subscribe to our YouTube Channel for WordPress video tutorials. You can also find us on Twitter and Facebook.

The post How to Select and Use Nested Blocks in WordPress first appeared on WPBeginner.

Writing a Vector Database in a Week in Rust

Category Image 073

Vector databases are currently all the rage in the tech world, and it isn't just hype. Vector search has become ever more critical due to artificial intelligence advances which make use of vector embeddings. These vector embeddings are vector representations of word embeddings, sentences, or documents that provide semantic similarity for semantically close inputs by simply looking at a distance metric between the vectors.

The canonical example from word2vec in which the embedding of the word "king" was very near the resulting vector from the vectors of the words "queen", "man", and "woman" when arranged in the following formula:

Chris’ Corner: Dreamy, Folded, Bendy CSS

Typography Definitions Cover

Yuan Chuan with a funny blog post opener commenting about how much they liked their friend’s photos:

I was attracted by their slight blur and the subtle glowing effects, and wondered what kind of filter function was used. But then she told me it’s just because the camera lens wasn’t wiped clean.

Turns out you can get that same kind of “dreamy” effect with some fancy dancing with filters.


Semantic HTML? Pffffft. Why bother? Unicode is all you really need.

Terence Eden says he is very sorry for this.

I probably should have just copied the unicode above into this email rather than screenshotting it, but it made me too nervous for some reason. Partially because I’d worry it looks like spam to some email servers.


Here’s a nice walkthrough of 3D in CSS by Brad Woods.

One of the demos has you grabbing the corner of an element with regular text in it, and as you drag it folds back in space, with, you guessed it 3D in CSS.

Seeing text in 3D is somehow extra satisfying for me, perhaps because it’s more rare to see. And hey, that reminds me of Codrops recent On-Scroll Typography Animations which are very very cool. Make sure to scroll far enough to see the “Unfolding” one which is my favorite.


I always though that the math behind calculating the perfect nested border-radius would be complex somehow. But Paul Hebert has it figured out for us:

outerRadius - gap = innerRadius

Gotta get this right folks! See how awkward it can be on the left vs. fixed on the right.

Chris’ Corner: Relatively Recent Great CSS Writing

Category Image 073

Chen Hui Jing, So your designer wants stuff to overlap

Love that title. Elements in HTML don’t just overlap each other by default. In fact, they intentionally push other elements around so that they don’t. You’ll need CSS to force elements to overlap if you need them to. The traditional ways:

  • negative margins
  • transform translate
  • absolute positioning

But Chen Hui Jing makes sure we don’t forget about grid! It might not come to mind immediately as we mostly think about making a grid and placing individual elements in individual grid cells. But grid cells don’t care! You can put as many elements as you want in a grid cell (or multiple grid cells). They are really just placement coordinates, not slots that only take one element.

Michelle Barker, Quick Tip: Negative Animation Delay

This is one of my favorite classic CSS tricks because it’s so obvious… but only after you’ve learned it. The point is mainly staggered animations. If you want animations to all be at different points along the same animation when they start animating, you can use animation-delay. But if you use a positive time value, the animation won’t start for the first time until that delay (duh). So instead, you use a negative value. The animation starts immediately, but backed up to where it needs to be to have the beginning of the animation hit once the negative delay elapses.

Charlotte Dann, Fancy Frames with CSS

Awesome research from Charlotte, covering lots of ways to make interesting “framed” shapes like these:

So is there one obvious clear best path forward to do this in CSS (and friends)? No — haha. Charlotte explores using 1️⃣ multiple gradient backgrounds (very complicated to construct, limitations with transparency), 2️⃣ border-image (one of the weirder CSS properties, but does help with placing gradients, or SVGs), 3️⃣ mask-border which I’m not sure I’ve ever even looked at in my life (no Firefox support), and finally, 4️⃣ Houdini which has no Firefox or Safari support, but does bring interesting JavaScript-powered opportunities into the mix.

Just to throw another one in the mix here… I happened to be playing with Open Props the other day and it has a “Mask Corner Cuts” section. It just uses mask (or -webkit-mask, as apparently the vendor-prefixed version alone gets the best support).

Scott Vandehey, The Power of CSS Blend Modes

Scott is inspired by other-Scott’s Pen (which happens to be #91 on the Top Pens of 2022 list) and breaks down exactly how it works. It’s a combination of filtering and blending layers. that’s just cool as heck.

You gotta go check out the article to see how Scott was able to stretch the idea to other effects, like a halftone filter.

Kate Rose Morley, Tree views in CSS

This is entirely doable in just semantic HTML and CSS alone:

The trick is putting all the list items that have a sub-list with a <details> element. The text of that <li> becomes whatever the <summary> is. Then you can style the ::marker of the details elements to have the plus-and-minus look rather than the default triangle. I appreciated Kate’s usage of :focus-visible too which keeps the focus styles away from mouse clicks.

11 Typography Styles to Consider for Your Next Design

Typography Definitions Cover

When it comes to typography, there’s a seemingly infinite number of styles to choose from. But which one is the right one for your next design?

That is the ultimate question when it comes to typography. And, unfortunately, there is no one-size-fits-all answer. It all depends on the specific project you’re working on and what kind of message you’re trying to communicate.

However, we can narrow it down to a few general categories.

Here are 11 popular typography styles to consider for your next project.

UNLIMITED DOWNLOADS: 400,000+ Fonts & Design Assets

Starting at only $16.50 per month!

1. Serif

01 - times new roman-Typography Styles

Serif fonts are the ones with the little feet (serifs) on the end of each letter. They are classic and elegant, and they have been around for centuries. Think of Times New Roman or Garamond – these are both serif fonts.

Serif fonts are generally seen as being more formal and traditional than other types of fonts. They are often used for headlines, logos, and other high-impact pieces.

2. Sans Serif

02 - sans serif-Typography Styles

Sans serif fonts are the exact opposite of serif fonts. They have no little feet on the end of the letters, hence the name “sans serif.”

Sans serif fonts are generally seen as being more modern and clean than serif fonts. They are often used for body copy, menus, and other pieces where readability is key.

3. Script

03 - adelia-Typography Styles

Script fonts are designed to look like they were written by hand. They are usually very flowing and cursive, and they can be difficult to read if they are used for large blocks of text.

Script fonts are best used for small pieces, such as headlines or logos. They can also be used for body copy, but only if the design is very simple and easy to read. A good example would be the Adelia Font.

4. Display

Display fonts are any type of font that is designed to be used at large sizes. They are often very bold and eye-catching, and they can be difficult to read at smaller sizes.

Display fonts are best used for headlines, logos, and other short pieces of text. They should not be used for body copy or any other type of long-form text. A good example that shows how bold these fonts can be is Arbutus.

5. Decorative

05 - space time - Typography Styles

Decorative fonts are just what they sound like – they are designed to be used for decorative purposes only. They are often very ornate and can be difficult to read.

Decorative fonts should only be used sparingly, if at all. They can be used for headlines or logos, but they should never be used for body copy. They are a lot of fun though. Just check out the Space Time font.

6. Blackletter

06- cloister black - Typography Styles

Blackletter fonts are a type of serif font that is designed to look like it was written in the Middle Ages. They are very ornate and can be difficult to read. It also goes by the name of gothic script or Old English.

Cloister Black is a great example of a blackletter font that encapsulates this old-fashioned style.

7. Handwritten

07 - autography

Handwritten fonts are designed to look like they were written by hand. They can be either serif or sans serif, but they usually have a more organic feel than other types of fonts.

Handwritten fonts are best used for small pieces, such as headlines or logos. The Autography Font illustrates this typography style well.

8. Slab Serif

08 - rosette

Slab serif fonts are a type of serif font that is designed to be used at large sizes. They are often very bold and eye-catching, and they can be difficult to read at smaller sizes.

Slab serif fonts are ideal for headlines, logos, and titles. They should not be used for body copy or any other type of long-form text though as the line weight is too thick for the confined spaces of paragraphs. The Rosette Font has a chunky look that serves as a good example of a slab serif.

9. Geometric

09 - geometric

Geometric fonts are designed to be very clean and simple. They often have straight lines and angles and rely on a geometric construction to achieve their letter shapes.

This kind of font is best used for headlines or logos, or any other spot where just a few words are needed. They can also be used for body copy, but only if the design is very simple, large, and easy to read.

10. Grotesque

10 - grotesque

Grotesque fonts are a type of sans serif font that is designed to be used at large sizes. Historically, they’re known for looking a bit awkward and unusual.

It is advisable to only use grotesque fonts for headlines, logos, and other brief pieces of text. They are not meant to be used for paragraphs or long stretches of text. Work Sans is a great example of a neo-grotesque style.

11. Humanistic

Humanistic fonts are sans serif fonts as well that are designed to look very natural and organic. They often have curved lines and softened edges.

Humanistic fonts are most successful when used for titles, headlines, or logos. They can also be readable if used sparingly in body copy with a simple design layout. You can look to the Centaur Font as a good example of this classic font style.

Let Typography Style Options Inspire You

There you have it! These are the 11 most common types of fonts that you’ll see used in graphic design. As you can see, each one has its own unique purpose and should be used accordingly.

When it comes to choosing the right font for your project, it’s important to think about the overall style you’re going for. Do you want something clean and modern? Or are you going for a more vintage or retro feel?

Once you have a general idea of the style you’re after, you can start browsing through different font options until you find one that fits your vision. Good luck!

Easy Fluid Typography With clamp() Using Sass Functions

Typography Definitions Cover

Fluid typography is getting a lot more popular, especially since the clamp() math function is available in every evergreen browser. But if we’re honest, it’s still a lot of mathematics to achieve this. You can use tools such as utopia.fyi, which are fantastic. But in large projects, it can get messy pretty fast. I’m a big fan of readable and maintainable code and always want to see what my code is doing at a glance. I’m sure there are many more of you like that, so instead of adding a full clamp() function inside of our code, maybe we can make this a bit more readable with Sass.

Why Should We Use Fluid Typography?

Usually, when designing for different screen sizes, we use media queries to determine the font size of our typographic elements. Although this usually gives enough control for the more conventional devices, it doesn’t cover all of the screen sizes.

By using fluid typography, we can make the typography scale more logically between all sorts of different devices.

This is now possible in all evergreen browsers because of the clamp() function in CSS. It is perfect for the job and reduces our media query writing, thus saving us a bit of file size along the way.

How Exactly Does This clamp() Function Work For Typography?

In short, the clamp function looks like this:

clamp([min-bound], [value-preferred], [max-bound]);

This takes into account three numbers: a minimum bound, preferred value, and a maximum bound. By using rem values, we can increase the accessibility a bit, but it’s still not 100% foolproof, especially for external browser tools.

If you want a more in-depth explanation of the math, I suggest you read this post from Adrian Bece “Modern Fluid Typography Using CSS Clamp ”.

However, there is a bit of a problem. When you read those clamp functions inside your CSS, it’s still hard to see exactly what is happening. Just imagine a file full of font sizes that look like this:

clamp(1.44rem, 3.44vw + 0.75rem, 2.81rem)

But with a little help from the sass function, we can make these font sizes much more readable.

What Do We Want To Achieve With This Simple Sass Function?

In short, we want to do something like this: We have a minimum font size, from the moment our breakpoint is larger than 400px, we want it to scale it to our biggest font size until the maximum breakpoint is reached.

The minimum and maximum font sizes are covered quite easily. If we want a minimum font size of 16px (or 1rem) and a maximum font size of 32px (or 2rem), we already have the two parts of our clamp function:

clamp(1rem, [?], 2rem)
Creating A Basic Automated Fluid Function

This is where things get tricky, and I suggest you follow the article by Adrian Bece, who gives a great in-depth explanation of the math behind this.

In short, the equation is the following:

(maximum font-size - minimum font-size) / (maximum breakpoint - minimum breakpoint)

Let’s get ready to do some mathematics for this to happen in Sass, so let’s create our fluid-typography.scss function file and start by adding sass:math and the function with the values we’ll need:

@use "sass:math";

@function fluid($min-size, $max-size, $min-breakpoint, $max-breakpoint, $unit: vw) {

}

Now, let’s add the calculation for the slope inside of our function with some sass:math:

@function fluid($min-size, $max-size, $min-breakpoint, $max-breakpoint, $unit: vw) {
 $slope: math.div($max-size - $min-size, $max-breakpoint - $min-breakpoint);
}

To get a value we can work with, we’ll need to multiply our slope by 100:

$slope-to-unit: $slope * 100;

All that is left is for us to find our intercept to build the equation. We can do this with the following function:

$intercept: $min-size - $slope * $min-breakpoint;

And finally, return our function:

@return clamp(#{$min-size}, #{$slope-to-unit}#{$unit} + #{$intercept}, #{$max-size});

If we call the created sass function in our scss, we should now get fluid typography:

h1 {
   font-size: #{fluid(1rem, 2rem, 25rem, 62.5rem)}
}

A Note About Units

In most cases, we will be using a viewport width when it comes to fluid typography, so this makes a good default. However, there are some cases, especially when using the clamp() function for vertical spacing, where you want to use a viewport height instead of width. When this is desired, we can change the outputted unit and use a minimum and maximum breakpoint for the height:

h1 {
   font-size: #{fluid(1rem, 2rem, 25rem, 62.5rem, vh)}
}
Updating The Function To Make The Calculations Feel More Natural

We got what we need, but let’s be honest, most of the time, we are implementing a design, and it doesn’t feel natural to pass our viewports as rems. So, let’s update this function to use pixels as a viewport measurement. While we’re at it, let’s update the font sizes so we can use pixel values for everything. We will still convert them to rem units since those are better for accessibility.

First, we’ll need an extra function to calculate our rem values based on a pixel input.

Note: This won’t work if you change your base rem value.

@function px-to-rem($px) {
    $rems: math.div($px, 16px) * 1rem;
    @return $rems;
}

Now we can update our fluid function to output rem values even though it gets pixels as input. This is the updated version:

@function fluid($min-size, $max-size, $min-breakpoint, $max-breakpoint, $unit: vw) {
    $slope: math.div($max-size - $min-size, $max-breakpoint - $min-breakpoint);
    $slope-to-unit: $slope * 100;
    $intercept-rem: px-to-rem($min-size - $slope * $min-breakpoint);
    $min-size-rem: px-to-rem($min-size);
    $max-size-rem: px-to-rem($max-size);
    @return clamp(#{$min-size-rem}, #{$slope-to-unit}#{$unit} + #{$intercept-rem}, #{$max-size-rem});
}

Now we can use the following input:

font-size: #{fluid(16px, 32px, 320px, 960px)}

This will result in the following:

font-size: clamp(1rem, 2.5vw + 0.5rem, 2rem);

At first glance, this seems perfect, but mostly that’s because I’ve been using very simple values. For example, when clamping to a maximum value of 31px instead of 32px, our rem values won’t be so rounded, and our output will get a bit messy.

Input:

font-size: #{fluid(16px, 31px, 320px, 960px)}

Output:

font-size: clamp(1rem, 2.34375vw + 0.53125rem, 1.9375rem);

If you’re like me and find this a bit messy as well, we could round our values a little bit to increase readability and save some bytes in our final CSS file. Also, it might get a bit tedious if we always have to add the viewport, so why not add some defaults in our function?

Rounding Our Values And Adding Some Defaults

Let’s start by adding a rounding function to our Sass file. This will take any input and round it to a specific amount of decimals:

@function round($number, $decimals: 0) {
    $n: 1;
    @if $decimals > 0 {
        @for $i from 1 through $decimals {
            $n: $n * 10;
        }
    }
    @return math.div(math.round($number * $n), $n);
}

Now we can update our output values with rounded numbers. Update the function accordingly. I would suggest setting at least two decimals for the output values for the most consistent results:

@function fluid($min-size, $max-size, $min-breakpoint, $max-breakpoint, $unit: vw) {
    $slope: math.div($max-size - $min-size, $max-breakpoint - $min-breakpoint);
    $slope-to-unit: round($slope * 100, 2);
    $intercept-rem: round(px-to-rem($min-size - $slope * $min-breakpoint), 2);
    $min-size-rem: round(px-to-rem($min-size), 2);
    $max-size-rem: round(px-to-rem($max-size), 2);
    @return clamp(#{$min-size-rem}, #{$slope-to-unit}#{$unit} + #{$intercept-rem}, #{$max-size-rem});
}

Now the same example as before will give us a much cleaner result.

Input:

font-size: #{fluid(16px, 31px, 320px, 960px)};

Output:

font-size: clamp(1rem, 2.34vw + 0.53rem, 1.94rem);

Adding A Default Breakpoint

If you don’t feel like repeating yourself, you can always set a default breakpoint to your function. Try updating the function like this:

$default-min-bp: 320px;
$default-max-bp: 960px;

@function fluid($min-size, $max-size, $min-breakpoint: $default-min-bp, $max-breakpoint: $default-max-bp, $unit: vw) {
    // ...
}

Now, we don’t need to repeat these viewports all the time. We can still add a custom breakpoint but a simple input such as:

font-size: #{fluid(16px, 31px)};

Will still result in:

font-size: clamp(1rem, 2.34vw + 0.53rem, 1.94rem);

Here is the full function:

@use 'sass:math';

$default-min-bp: 320px;
$default-max-bp: 960px;

@function round($number, $decimals: 0) {
    $n: 1;
    @if $decimals > 0 {
        @for $i from 1 through $decimals {
            $n: $n * 10;
        }
    }
    @return math.div(math.round($number * $n), $n);
}

@function px-to-rem($px) {
    $rems: math.div($px, 16px) * 1rem;
    @return $rems;
}

@function fluid($min-size, $max-size, $min-breakpoint: $default-min-bp, $max-breakpoint: $default-max-bp, $unit: vw) {
    $slope: math.div($max-size - $min-size, $max-breakpoint - $min-breakpoint);
    $slope-to-unit: round($slope * 100, 2);
    $intercept-rem: round(px-to-rem($min-size - $slope * $min-breakpoint), 2);
    $min-size-rem: round(px-to-rem($min-size), 2);
    $max-size-rem: round(px-to-rem($max-size), 2);
    @return clamp(#{$min-size-rem}, #{$slope-to-unit}#{$unit} + #{$intercept-rem}, #{$max-size-rem});
}
A Final Note: Be A Happy Clamper For All users Out There

If you followed this little tutorial and were amazed by it, you might want to add this clamp() method for everything, but there is an important side note when it comes to accessibility.

Note: When you use vw units or limit how large text can get with clamp(), there is a chance a user may be unable to scale the text to 200% of its original size.

If that happens, it is WCAG failure. As Adrian Bece mentioned, it’s not 100% foolproof. Adrian Roselli has written some examples on this, which you might find interesting.

We can use this method today because of the great browser support. By being smart on the usage, I’m sure it can be a beautiful addition to your upcoming project or as an upgrade to a previous one.