- Published on
Vertical Align and Scrollable Elements in Tailwind Without Scrollbar
- Authors
- Name
- Ripal & Zalak
How to Vertically Align a Div with Tailwind CSS
When working with Tailwind CSS, you might want to vertically center an element inside a full-screen div
. You can achieve this easily using either Flexbox or CSS Grid utilities provided by Tailwind.
Solution 1: Using Flexbox
Tailwind CSS makes centering elements simple with flex
, justify-center
, and items-center
.
<div class="flex h-screen items-center justify-center bg-gray-200">
<div class="rounded bg-white p-8 text-center shadow-lg">
<h3 class="text-lg font-semibold">Centered Heading</h3>
<button class="mt-2 rounded bg-blue-500 px-4 py-2 font-bold text-white">Call to Action</button>
</div>
</div>
Solution 2: Using CSS Grid
Alternatively, you can use CSS Grid for a cleaner approach.
<div class="grid h-screen place-items-center bg-gray-200">
<div class="rounded bg-white p-8 text-center shadow-lg">
<h3 class="text-lg font-semibold">Centered Heading</h3>
<button class="mt-2 rounded bg-blue-500 px-4 py-2 font-bold text-white">Call to Action</button>
</div>
</div>
Creating a Scrollable Element Without a Scrollbar in Tailwind
If you need a scrollable container without a visible scrollbar, Tailwind provides a combination of overflow-auto
and CSS tricks to hide scrollbars.
1. Hide Scrollbar Using Tailwind and CSS
You can add a custom class to hide the scrollbar:
/* Hide scrollbar for Chrome, Safari, and Opera */
.no-scrollbar::-webkit-scrollbar {
display: none;
}
/* Hide scrollbar for IE, Edge, and Firefox */
.no-scrollbar {
-ms-overflow-style: none; /* IE and Edge */
scrollbar-width: none; /* Firefox */
}
2. Use Tailwind Utility Class in Your HTML
<div class="no-scrollbar h-64 w-full overflow-auto bg-gray-100 p-4">
<p>Scrollable content goes here...</p>
<p>More content...</p>
<p>Keep scrolling...</p>
</div>
3. Alternative: Add Custom Tailwind Plugin
Modify tailwind.config.js
to include a utility class for hiding scrollbars:
const plugin = require('tailwindcss/plugin')
module.exports = {
content: ['./pages/**/*.{js,ts,jsx}', './components/**/*.{js,ts,jsx}'],
theme: {
extend: {},
},
plugins: [
plugin(function ({ addUtilities }) {
addUtilities({
'.scrollbar-hide': {
'-ms-overflow-style': 'none',
'scrollbar-width': 'none',
'&::-webkit-scrollbar': { display: 'none' },
},
})
}),
],
}
Now, you can use scrollbar-hide
in your HTML:
<div class="scrollbar-hide h-64 w-full overflow-auto bg-gray-100 p-4">
<p>Content inside a hidden scrollbar container.</p>
</div>