- Published on
How to Center a Button in TailwindCSS
- Authors
- Name
- Ripal & Zalak
How to Center a Button in TailwindCSS
Centering elements, such as buttons, in TailwindCSS is straightforward once you understand its utility classes. If you're struggling to center a button inside a div
, here's a complete guide.
Common Issue
You might have tried classes like justify-center
, items-center
, mx-auto
, or content-center
, but the button still aligns to the left. This happens because these classes need to be applied to the correct container and context. Here's how to do it right.
Step-by-Step Solutions
1. Using Flexbox
Flexbox is one of the most common methods to center elements.
<div class="container mx-auto flex min-w-full flex-col items-center px-10 py-10">
<h2 class="mb-3 text-5xl text-black">Contact Us</h2>
<p class="text-black">
Kickstart your career in BioPharma with the Mendeleev Institute right now
</p>
<button class="mt-3 rounded bg-purple-900 px-4 py-2 font-bold text-white hover:bg-blue-400">
Learn More
</button>
</div>
Explanation:
flex
: Enables Flexbox on the container.flex-col
: Stacks children vertically.items-center
: Aligns children horizontally at the center.
2. Using Grid
CSS Grid is another great way to center elements.
<div class="container mx-auto grid min-w-full place-items-center px-10 py-10">
<h2 class="text-center text-5xl text-black">Contact Us</h2>
<p class="text-center text-black">
Kickstart your career in BioPharma with the Mendeleev Institute right now
</p>
<button class="mt-3 rounded bg-purple-900 px-4 py-2 font-bold text-white hover:bg-blue-400">
Learn More
</button>
</div>
Explanation:
grid
: Enables Grid layout on the container.place-items-center
: Centers items both horizontally and vertically.
text-center
for Simpler Layouts
3. Using If the button is the only element to center and you don’t want to use Flexbox or Grid:
<div class="container mx-auto min-w-full px-10 py-10">
<h2 class="text-center text-5xl text-black">Contact Us</h2>
<p class="text-center text-black">
Kickstart your career in BioPharma with the Mendeleev Institute right now
</p>
<p class="text-center">
<button class="mt-3 rounded bg-purple-900 px-4 py-2 font-bold text-white hover:bg-blue-400">
Learn More
</button>
</p>
</div>
Explanation:
- Wrapping the button inside a
<p>
tag withtext-center
centers the button horizontally.
Frequently Asked Questions (FAQ)
mx-auto
center my button?
1. Why doesn’t mx-auto
only works on block-level elements and requires a defined width. Ensure the button has a block
or inline-block
display property.
items-center
and justify-center
?
2. What’s the difference between items-center
: Aligns items along the cross-axis (vertical forflex-row
).justify-center
: Aligns items along the main axis (horizontal forflex-row
).
3. Which method is best for responsive design?
Both Flexbox and Grid are responsive-friendly. Use Grid for complex layouts and Flexbox for simpler ones.