将元素固定在等高卡片的底部

Preview of the 3 content cards with equal heights and the buttons sticking at the bottom

In the following code snippet, we’ll show you how to create content cards with Tailwind CSS. These cards have two main features: they all have the same height, no matter what’s inside, and the buttons inside the cards are always positioned at the bottom, no matter how tall they are.

在下面的代码片段中,我们将向您展示如何使用Tailwind CSS创建内容卡片。这些卡片具有两个主要特点:无论内部内容如何,它们的高度都相同,并且卡片内部的按钮始终位于底部,无论它们有多高。

To ensure consistent card height despite different content, you have two choices: you can use the flexbox model or, as shown here, use a CSS grid layout. The key to keeping card height consistent is making sure the card element, styled with a white background (bg-white), stretches to 100% of its parent’s height (h-full).

为了确保卡片高度一致,不论内容如何,您有两个选择:您可以使用flexbox模型,或者如本例所示,使用CSS网格布局。保持卡片高度一致的关键是确保卡片元素使用白色背景(bg-white)样式,并且将其拉伸到父元素的高度的100%(h-full)。

With that setup, let’s move on to setting up the card’s content. The image is given a fixed height of 192px (h-48). Next, we have the element containing the text and buttons. Since we’ve used the flex and flex-col classes on its parent, we can ensure this element takes up all available space with flex-1.

有了这个设置,让我们继续设置卡片的内容。图像的高度固定为192px(h-48)。接下来,我们有包含文本和按钮的元素。由于我们在其父元素上使用了flexflex-col类,我们可以使用flex-1确保此元素占用所有可用空间。

Now, we can make the buttons stick at the bottom of the card in two ways:

现在,我们可以以两种方式使按钮固定在卡片底部

  • By applying the mt-auto class to the element containing the buttons
  • 通过将mt-auto类应用于包含按钮的元素
  • Alternatively, we can use the flex-1 class to the element containing the text to make it expand and push the buttons downward
  • 或者,我们可以对包含文本的元素使用flex-1类,使其扩展并将按钮向下推

As you’ve seen, CSS offers different methods to achieve the same result. We’ve shown one approach in our example, but feel free to experiment and find the solution that works best for you!

正如您所见,CSS提供了不同的方法来实现相同的结果。我们在示例中展示了一种方法,但请随意尝试并找到最适合您的解决方案!

Code

代码

<div class="max-w-xs mx-auto grid gap-6 lg:grid-cols-3 items-start lg:max-w-none"> <!-- Card --> <div class="flex flex-col h-full bg-white border border-slate-200 shadow shadow-slate-950/5 rounded-...
开通本站会员,查看完整译文。

首页 - Wiki
Copyright © 2011-2024 iteam. Current version is 2.137.3. UTC+08:00, 2024-11-26 10:08
浙ICP备14020137号-1 $访客地图$