Home > Enterprise >  Vertically center align a div within a div
Vertically center align a div within a div

Time:11-29

I have got a responsive two-column layout page. When the size of the screen is down to tablet, it becomes a single-column layout, where the first column wont be visible anymore. I have got a div inside the second div, and I want this to be vertically centre aligned.

I am using tailwind along with flexbox.

This is my code so far

    <div className="flex min-h-full">
      <div className="flex-none w-1/3 min-h-full hidden lg:block">
        01
      </div>
      <div className="grow md:bg-slate-100 h-screen">
         <div className="bg-red-400 h-3/5 mx-16"></div>
      </div>
    </div>

I have tried various options but I am struggling to have the inner div to be center alligned. Currently its sticking to top.

CodePudding user response:

If you are working with the tailwind, you can use the align-middle class to make the text vertically centered.

CodePudding user response:

Apply relative, -translate-y-1/2 and top-[50%] on the inner div.

You can find a similar solution using CSS here.

Because we want to apply those utilities on smaller screens (with the lg: breakpoint prefix), we need to set the default value on bigger screens. We have two options, either we apply all the utilities, including the default ones, on the inner div. Or, we create a custom class. By creating a custom class, we will have a much cleaner list of classes.


Applying the utilities directly on the inner div:

<div >
  <div >01</div>
  <div >
    <div ></div>
  </div>
</div>

Tailwind-play


Creating a custom class:

HTML:

<div >
  <div >01</div>
  <div >
    <div ></div>
  </div>
</div>

CSS:

@tailwind base;
@tailwind components;
@tailwind utilities;

@layer utilities {
   .responsive-align {
     @apply relative lg:block -translate-y-1/2 lg:-translate-y-0 top-[50%] lg:top-0;
   }
}

Tailwind-play

You can read more about adding custom classes here.

  • Related