DEV Community

Mykolas Mankevicius
Mykolas Mankevicius

Posted on

Add clamped sizes to TailwindCSS

Here's a little snippet i use to easily create responsive spacing/text sized.

const remToPX = (rem) => rem * 16
const pxToRems = (px) => px / 16

const formatNumber = (num) => parseFloat(num.toFixed(3)).toString()

const clamped = (minPx, maxPx, minBp, maxBp) => {
  const slope = (maxPx - minPx) / (maxBp - minBp)
  const slopeVw = formatNumber(slope * 100)
  const interceptRems = formatNumber(pxToRems(minPx - slope * minBp))
  const minRems = formatNumber(pxToRems(minPx))
  const maxRems = formatNumber(pxToRems(maxPx))
  return `clamp(${minRems}rem, ${slopeVw}vw + ${interceptRems}rem, ${maxRems}rem)`
}
const MIN_VIEWPORT_WIDTH = 400
const MAX_VIEWPORT_WIDTH = 1000
const clampPx = (minPx, maxPx) => clamped(minPx, maxPx, MIN_VIEWPORT_WIDTH, MAX_VIEWPORT_WIDTH)
const clampRem = (minRem, maxRem) => clamped(remToPX(minRem), remToPX(maxRem), MIN_VIEWPORT_WIDTH, MAX_VIEWPORT_WIDTH)
Enter fullscreen mode Exit fullscreen mode

And i use it like so in the tailwind.config.js

    fontSize: {
      '32_48': [
        clampPx(32, 48),
        clampPx(38, 56),
      ],
    },
    spacing: {
        '32_60': clampPx(32, 60),
        '32_64': clampPx(32, 64),
    }
Enter fullscreen mode Exit fullscreen mode

Which allows me to create responsive spacing based on viewport width like so:

Image description

It's all based on this excellent work:

https://github.com/AleksandrHovhannisyan/fluid-type-scale-calculator

Don't forget to like and share please! :D

SurveyJS custom survey software

Build Your Own Forms without Manual Coding

SurveyJS UI libraries let you build a JSON-based form management system that integrates with any backend, giving you full control over your data with no user limits. Includes support for custom question types, skip logic, an integrated CSS editor, PDF export, real-time analytics, and more.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more