How to Horizontally and Vertically Center an Element in Tailwind CSS ?
Last Updated :
06 Feb, 2024
To horizontally and vertically center an element in Tailwind CSS, you can use the combination of flexbox and alignment utility classes. Apply flex
and alignment classes to the parent container, and use mx-auto
and my-auto
for horizontal and vertical centering respectively.
Syntax
<div class="flex items-center justify-center h-screen">
<div class="bg-gray-300 p-4">
<!-- Your content here -->
</div>
</div>
Classes
Class |
Description |
flex |
Establishes a flex container, enabling a flexible box layout for its child elements. |
items-center |
Aligns items along the horizontal axis at the centre, facilitating horizontal alignment of child elements. |
justify-center |
Centres items along the vertical axis, ensuring vertical alignment of child elements within the flex container. |
h-screen |
Sets the height of the container to the full-screen height, making it occupy the entire vertical space of the viewport. |
mx-auto |
Sets the margin on the horizontal axis to auto, achieving horizontal centring for the container or element. |
Key Features
- Flexbox Layout: Utilizes flexbox to create a flexible container for easy horizontal and vertical centering.
- Responsive Design: The approach is responsive, adapting to different screen sizes using Tailwind’s responsive variants.
- No Custom CSS: Achieve centering without the need for custom CSS rules, following Tailwind’s utility-first approach.
Share your thoughts in the comments
Please Login to comment...