【问题标题】:Vertically center align a div within a divVertically center align a div within a div
【发布时间】:2022-12-27 15:53:28
【问题描述】:

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.

【问题讨论】:

  • 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

标签: css flexbox tailwind-css


【解决方案1】:

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

【讨论】:

  • 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
【解决方案2】:

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.

【讨论】:

    猜你喜欢
    • 2012-03-18
    • 1970-01-01
    • 2012-03-18
    • 1970-01-01
    • 2017-01-29
    • 2012-05-18
    • 2022-11-19
    • 1970-01-01
    • 2011-08-15
    相关资源
    最近更新 更多