乐闻世界logo
搜索文章和话题

How to center vertically and horizontaly a div with Tailwind CSS

1个答案

1

When using TailwindCSS for styling, achieving horizontal and vertical centering of a div can be done by leveraging Tailwind's Flexbox utility classes. Here are the specific steps and examples:

  1. Create a container (div): First, you need a div element to serve as the container for the content you want to center.
  2. Set Flexbox properties: On this div element, apply the flex class to define the flexbox layout.
  3. Enable centering alignment:
    • Use the items-center class to vertically center child elements.
    • Use the justify-center class to horizontally center child elements.

Example code:

html
<div class="flex items-center justify-center h-screen"> <div class="bg-blue-500 text-white p-4"> I am centered content </div> </div>

In this example:

  • The outermost div uses the flex, items-center, and justify-center classes, causing all child elements to be centered both horizontally and vertically.
  • We add the h-screen class to set the container's height to the full screen height, making the centering effect more apparent.
  • The inner div contains the actual content, and we set its background color, text color, and padding.

After this setup, regardless of page size changes, the inner div will remain centered on the screen. This is a highly effective and commonly used method for achieving content centering with TailwindCSS.

2024年6月29日 12:07 回复

你的答案