DEV Community

Cover image for TailwindCSS Arbitrary values. Free UI/UX design course
Keep Coding
Keep Coding

Posted on • Updated on

TailwindCSS Arbitrary values. Free UI/UX design course

Arbitrary values

Arbitrary value support in Tailwind CSS allows you to use any custom value with any utility where it makes sense. It's a powerful feature introduced in Tailwind CSS v2.2. This means you're no longer limited by the values defined in your configuration file and can use any value you need right in your HTML.

For example, if you want to set a width that isn't available in Tailwind CSS classes, you can now do so like this:

HTML
<div class="w-[123px]">[...]</div>

In the above example, [123px] is an arbitrary value that sets the width of the element to 123px.

Arbitrary values with modifiers

You can also use arbitrary values with responsive design, hover state, etc:

HTML
<div class="hover:w-[123px] md:w-[456px]">[...]</div>

In this example, the width of the element will be 456px on medium screens (md:w-[456px]), and the width will change to 123px on hover (hover:w-[123px]).

This feature also supports other units, not just pixels. You can use rem units, percentages, etc. Additionally, you can use this feature with most of the utility classes in Tailwind CSS, such as padding, margin, translate, scale, rotate, skew, grid, etc.

Arbitrary values give you a lot more flexibility and power when using Tailwind CSS. They allow you to have the benefits of utility-first CSS while still being able to use any value you need, right in your markup.

Fixing the Hero Image using arbitrary values

In the previous lesson, we finished our fullscreen Hero Image. On large screens, it fills the available space perfectly, down to the pixel.

Image description

However, there is a problem in the mobile view - there is a small, empty space at the bottom.

Image description

That's because Navbar is a flexible component and adapts to its content. In the mobile view, the Navbar collapses and hides most of its elements, which reduces its height.

And as you remember, we set our Hero Image margin-top: -56px; , because that's the height of the Navbar on large screens.

So we need to make sure that on other screen sizes the height of the Navbar stays the same, which is 56px.

This is the perfect opportunity to use arbitrary values.

Add min-h-[56px] to Navbar.

The min-h- class defines the minimum height for a given element, and [56px] is the height given in the form of arbitrary values that we want to maintain on all screens.

HTML

<!-- Navbar -->
<nav
  class="flex-no-wrap relative flex min-h-[56px] w-full items-center justify-between bg-white py-2 shadow-md shadow-black/5 dark:bg-neutral-600 dark:shadow-black/10 lg:flex-wrap lg:justify-start lg:py-4"
  data-twe-navbar-ref>
  [...]
</nav>
Enter fullscreen mode Exit fullscreen mode

Now it's pixel-perfect on every screen size 🤩

Image description

DEMO AND SOURCE CODE FOR THIS LESSON

Top comments (0)