- Published on
How to Create One-Sided Shadows with TailwindCSS
- Authors
- Name
- Ripal & Zalak
Introduction
Creating a shadow that appears on only one side of an element using TailwindCSS isn't straightforward with its built-in utilities, as classes like shadow-lg apply shadows uniformly to all sides. In this guide, we'll explore two methods to achieve a one-sided shadow effect: using arbitrary values and leveraging plugins.
The Problem
Using a TailwindCSS class like shadow-lg adds a shadow to all sides of an element, which might not fit your design requirements when you need a shadow on just one side, such as the right or bottom side.
Solution 1: Using Arbitrary Values
TailwindCSS allows you to use arbitrary values for shadows. This provides a way to define precise offsets and create a shadow on one side.
Here’s an example:
<div class="relative h-screen bg-gray-100">
<div
class="absolute inset-20 h-12 w-36 rounded-lg bg-blue-500 shadow-[10px_0_15px_rgba(0,0,0,0.3)]"
>
One-Sided Shadow
</div>
</div>
Explanation
shadow-[10px_0_15px_rgba(0,0,0,0.3)]: This defines a custom shadow:10px: Horizontal offset (positive for right, negative for left).0: Vertical offset.15px: Blur radius.rgba(0,0,0,0.3): Color of the shadow.
You can adjust these values to control the position, size, and intensity of the shadow.
Solution 2: Using Tailwind Plugins
For more flexibility, you can use a plugin like tailwind-extended-shadows. This plugin provides utilities for specifying shadow directions and spread, making it easier to achieve one-sided shadows without relying on arbitrary values.
Installation
- Install the plugin:
npm install tailwind-extended-shadows
- Add the plugin to your
tailwind.config.jsfile:
const extendedShadows = require('tailwind-extended-shadows')
module.exports = {
content: ['./src/**/*.{html,js}'],
theme: {
extend: {},
},
plugins: [extendedShadows],
}
Usage
Now you can use directional shadow utilities:
<div class="shadow-r-[10px] shadow-spread-[-2px] shadow-lg shadow-black/20">
One-Sided Shadow with Plugin
</div>
Explanation
shadow-r-[10px]: Applies a shadow to the right side with a 10px offset.shadow-spread-[-2px]: Adjusts the shadow spread, pulling it closer to the element.shadow-black/20: Sets the shadow color and transparency.
FAQ
Q1: Can I achieve one-sided shadows without plugins?
Yes, you can use Tailwind's arbitrary values for shadows, as shown in Solution 1. Plugins like tailwind-extended-shadows provide a more structured approach.
Q2: What’s the benefit of using plugins over arbitrary values?
Plugins offer pre-defined utilities and better readability in your code, especially in large projects.
Q3: Can I combine these methods?
Absolutely! You can use plugins alongside arbitrary values for maximum flexibility in your designs.
