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

How to fill the height of the viewport with tailwind css

7 个月前提问
3 个月前修改
浏览次数154

6个答案

1
2
3
4
5
6

在Tailwind CSS中,如果您希望建立一个元素填充整个视口的高度,可以使用h-screen工具类。这个类的意思是将元素的高度设置为100vh(viewport height,即视口高度)。

例如,如果您有一个容器,您希望它占据整个浏览器窗口的高度,您可以像这样添加类:

html
<div class="h-screen"> <!-- 内容 --> </div>

这个div将会扩展以填满整个视口的高度。

此外,如果您想要一个高度稍微小于100vh的元素,比如考虑到浏览器的地址栏或者底部导航,您可以使用min-h-screen来确保元素至少和视口一样高,但可以根据内容的多少变得更高。

如果您需要更细粒度的控制,可以使用vh单位和自定义的高度工具类,例如:

html
<div class="h-[50vh]"> <!-- 内容 --> </div>

这将设置元素的高度为视口高度的50%。

Tailwind CSS提供了响应式的工具类,所以如果您需要在不同的屏幕尺寸下有不同的高度,可以使用前缀来指定:

html
<div class="h-screen md:h-[75vh] lg:h-[90vh]"> <!-- 内容 --> </div>

在这个例子中,元素默认会占据整个视口的高度,但在中等大小的设备上(md),它的高度将变为视口高度的75%,而在大型设备上(lg),它的高度将变为视口的90%。

总之,使用Tailwind CSS的视口高度工具类是一个快速且响应式的方法来控制元素的高度,确保它们能够适应不同设备的显示需求。

2024年6月29日 12:07 回复

There is a tailwind class named .h-screen that translates to height:100vh; css. This should work as well. For further details please refer to the Official Tailwind documentation

2024年6月29日 12:07 回复

You can add min-h-screen to the parent <div>, this would fill the height of the viewpoint.

And the difference with h-screen is that this will stretch over the screen. It would be helpful when the screen is tiny and the content is overflowing with a scrollbar. In this situation the background will not fill the rest of the scrolled-up part.

shell
<div class="flex items-stretch bg-grey-lighter min-h-screen"> <div class="flex-1 text-grey-darker text-center bg-grey-light px-4 py-2 m-2">1</div> <div class="flex-1 text-grey-darker text-center bg-grey-light px-4 py-2 m-2">2</div> <div class="flex-1 text-grey-darker text-center bg-grey-light px-4 py-2 m-2">3</div> </div>

Link to some snippets at tailwind play (added a background color example to clarify it): https://play.tailwindcss.com/8Qd822yY4w

2024年6月29日 12:07 回复

You can use .h-screen class of Tailwind CSS.

2024年6月29日 12:07 回复

I'm using NextJS + tailwindcss. NextJS adds a <div id="__next">, so this is what I have in my global.css

shell
@tailwind base; @tailwind components; @tailwind utilities; html { @apply h-full; } body { @apply h-full; } div#__next { @apply h-full; } main { @apply h-full; }

And in my page I have

shell
<main className="bg-gradient-to-br from-indigo-500 via-purple-500 to-pink-500"> ... </main>
2024年6月29日 12:07 回复

I know it's an old post, but I found it now, while I was trying to have the background color streched to the size of the screen when the content was too little to fill it and avoid to have the background color to stop suddenly when the content was more of the size of the screen (that happens with h-screen). I solved the problem using min-h-screen.

2024年6月29日 12:07 回复

你的答案