1

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 aligned. Currently its sticking to top.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Libin Joseph
  • 7,070
  • 5
  • 29
  • 52
  • Can you please provide more clarity to the question , may be a pictorial representation of what you are expecting the result to be as .. That would help – krishnaacharyaa Nov 29 '22 at 01:57

2 Answers2

0

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

Mubeen Ahmad
  • 428
  • 3
  • 11
  • I have tried it, and it does not make any difference. Also please note, I have trying to center align a div and not text – Libin Joseph Nov 28 '22 at 12:44
0

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 class="flex min-h-full">
  <div class="hidden min-h-full w-1/3 flex-none lg:block">01</div>
  <div class="h-screen grow md:bg-slate-100 ">
    <div class="mx-16 h-3/5 bg-red-400 relative lg:block -translate-y-1/2 lg:-translate-y-0 top-[50%] lg:top-0"></div>
  </div>
</div>

Tailwind-play


Creating a custom class:

HTML:

<div class="flex min-h-full">
  <div class="hidden min-h-full w-1/3 flex-none lg:block">01</div>
  <div class="h-screen grow md:bg-slate-100 ">
    <div class="mx-16 h-3/5 bg-red-400 responsive-align"></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.

ChenBr
  • 1,671
  • 1
  • 7
  • 21