Applying font size constraints in TailwindCSS

Is it possible to implement the clamp() CSS function with TailwindCSS in order to create linear scaling for the fontSize within a defined range?

I am specifically curious about how this can be integrated with Next.js.

Answer №1

As of the current writing, TailwindCSS does not appear to have native support for clamp() by default.

A search brings up a case for implementing multi-line truncation using the line-clamp plugin, which serves a different purpose from clamping font sizes.

Following the idea from this GitHub discussion, incorporating clamp() in TailwindCSS can be achieved by extending the default theme. Example in a Next.js application:

/** @type {import('tailwindcss').Config} */
module.exports = {
  content: [
    "./app/**/*.{js,ts,jsx,tsx,mdx}",
    "./pages/**/*.{js,ts,jsx,tsx,mdx}",
    "./components/**/*.{js,ts,jsx,tsx,mdx}",

    // Or if using `src` directory:
    "./src/**/*.{js,ts,jsx,tsx,mdx}",
  ],
  theme: {
    extend: {
      fontSize: {
        clamp: "clamp(1rem, 5vw, 3rem)",
      },
    },
  },
  plugins: [],
};

For usage in a jsx or tsx component, simply include text-clamp as an additional className.

https://i.sstatic.net/68Hsx.gif

Link to functional codesandbox.

Answer №2

You won't find a ready-made Tailwind utility class for this task, but you can achieve it by implementing custom CSS using Tailwind's Arbitrary properties feature

For instance:


<p class="[font-size:_clamp(1.5rem,4vw,3rem)]">Content</p>

Answer №3

Although it may not be the most aesthetically pleasing, assigning an arbitrary value to text- will dictate the font-size:

<div class="text-[clamp(1.25rem,3cqw,3rem)]">
  Just ensure that there are no spaces in the class name
</div>

You can also create a simple plugin to enhance the appearance.

tailwind.config.js:

const plugin = require('tailwindcss/plugin');

/** @type {import('tailwindcss').Config} */
module.exports = {
  // ...
  plugins: [
    // ...
    plugin(({matchUtilities, theme}) => {
      matchUtilities(
        {
          clamp(value) {
            // fetching font sizes from theme
            const sizes = theme('fontSize');

            // parsing the value from class name
            // breaking it down by "-" and comparing components to fontSize values
            const split = value
              .split('-')
              .map(v => sizes[v] ? sizes[v]['0'] : v);
            
            // returning a clamped font-size
            return {
              fontSize: `clamp(${split[0]}, ${split[1]}, ${split[2]})`,
            }
          }
        }
      );
    }),
  ]
}

Then apply it as a class like so:

<div class="clamp-[xl-3cqw-5xl]">
  still not the most elegant, but improved. 
</div>

Check out a modified version of the mentioned code-sandbox.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Organize your table with CSS styling

Looking for a way to rearrange a table with 2 columns after every 2 rows so that the lines continue on the right side? Check out the example below: [1][2] [1][2][5][6] [3][4] => [3][4][7][8] [5][6] [7][8] Wondering if this can be achieved using o ...

A modern CSS solution for a fixed columns and header layout in a scrollable table

How can I create a table with minimal JavaScript using modern CSS? I am aiming to include the following features: Fixed column(s) (positioning and width) Scrollable in both X and Y axes Responsive in the X axis (for non-fixed width columns). https://i. ...

Modify the parent div's background color on mouseover of the child li

I want to update the background image of a parent div that contains a series of ul li elements. Here is the HTML code I am working with: <section class="list" id="services"> <div class="row"> <ul> <li>& ...

Tips for maintaining real-time data accuracy with Socket.io for a substantial dataset

In my current project, I am developing a system that handles multiple user types with varying levels of access to interact with the database resources. It is essential for me that these resources are displayed in real-time to ensure a seamless user experie ...

Axios is not properly executing the post request

While attempting to submit data using axios in NodeJS and ReactJS, I encountered the following errors: https://i.sstatic.net/3FM6o.png https://i.sstatic.net/XZ0iS.png Here is the code I used for posting: axios({ method: 'post', url: ...

What is the best way to place a parent div above its child element?

I'm currently dealing with a container div styled with background-color: red;. This container has around 12 children, and the last child is set with background-color: blue;. My goal was to position the container on top of the child with the blue backg ...

Creating a symbolic link between a React component library and a Next.js application for testing purposes

My React component library functions as a micro frontend service, built and running with the following technologies: React Typescript Styled-components Storybook Rollup I have successfully published the component library as a package to GitHub/npm and im ...

Adjust the Navbar to be Aligned Completely to the Left and Divide it into 12

I need my navbar to be split into 12 sections so that each item occupies one section, starting from the far left of the screen. The current alignment doesn't meet this requirement as shown in the image below; https://i.sstatic.net/irYqV.png Despite ...

Tips for expanding an input to fit the width of a div without altering the dimensions of a preceding span element

Let me explain, I have a form that includes a span and an input: <form onSubmit={e => handleSubmit(e)}> <Box className='form_box'> <span> <a href="/cd ...

Display your StencilJs component in a separate browser window

Looking for a solution to render a chat widget created with stenciljs in a new window using window.open. When the widget icon is clicked, a new window should open displaying the current state while navigating on the website, retaining the styles and functi ...

retrieve the height value of a div element using AngularJS

I'm having trouble retrieving the updated height of a div using AngularJS. It seems to only provide the initial value and does not update as expected: vm.summaryHeight = $(".history-log-container").height(); console.log(vm.summaryHeight);//always dis ...

Enhance your Next.js routing by appending to a slug/url using the <Link> component

In my Next.js project, I have organized my files in a folder-based structure like this: /dashboard/[appid]/users/[userid]/user_info.tsx When using href={"user_info"} with the built-in Next.js component on a user page, I expect the URL to dynamic ...

The art of perfect alignment: Mastering the positioning of Material-UI Grid

This issue has been resolved Hey there, I'm currently working on a React App with Material-UI and I'm trying to center a Grid item that includes a Card along with two additional Grid items. Below is the relevant code snippet. Although the Cards ...

Surprising outcome experienced in the realm of React

After conducting an AJAX request, I'm storing the fetched data into the state variable. However, when I attempt to print it in the console using the provided code snippet, the array appears to be empty. state = { addressOject: [] }; view = valu ...

Are you in need of a flexbox list that can be scrolled

How can I create a scrollable ul element? Currently, it appears that the ul flexbox extends beyond the browser window. html <div class="container"> <div class="header"> Untitled </div> <ul/> <li>1</li> ...

Hover your mouse cursor over the React Material UI TextField to see the icon

I am trying to customize the mouse cursor behavior of a TextField component from Material UI when its variant is set to "outlined". Currently, the cursor changes to Text but I want it to appear as a pointer instead. I attempted to override the default beha ...

Only display one div element when in print mode, hiding all others

My print style CSS code includes the following: * { display:none; } #printableArea { display:block; } Initially, I anticipated that this CSS would hide all elements except for the printableArea. Surprisingly, everything on the page became hidden when ...

D3 Chart: What is the best way to insert images into a node?

Within the jsFiddle demo provided in this query, there is code displayed. I am curious about how I can assign images to each node. var graph = { "nodes":[ {"name":"1","rating":90,"id":2951}, ] } You can access my jsFiddle Demo through this ...

What is causing the difficulty in accessing the 'query' feature within the API, and why is the question bank failing to display?

Just wanted to mention that I am still learning about class based components, setState, and other concepts in async JS like axios. Below is a very basic example of what I can currently do. This is App.js: import Questions from './components/Ques ...

CSS is altering the background color to a slightly modified tint from its original shade

After uploading a high-definition image as a background, I noticed that in the DOM the file appeared to have a slightly greener tint than the original. However, upon inspecting the image background element and saving it again, it saved with the original ti ...