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

How to use fixed sticky in tailwindcss

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

6个答案

1
2
3
4
5
6

在TailwindCSS中,fixedsticky是用来设置元素定位的实用类。下面我会分别解释它们的用法,并给出一些例子。

Fixed 定位

fixed 属性在 TailwindCSS 中对应的类是 fixed,它会将元素的定位设置为固定(fixed),意味着元素会相对于浏览器窗口进行定位,并且即使页面滚动,元素也会停留在设置的位置上。

例子

假设我们想要创建一个固定在视口顶部的导航栏:

html
<div class="fixed top-0 left-0 right-0"> <!-- 导航栏的内容 --> </div>

上面的代码将导航栏固定在页面的顶部。top-0left-0,和 right-0 是 TailwindCSS 中的辅助类,它们分别将导航栏的顶部、左边和右边定位到视口的边缘。

Sticky 定位

sticky 定位是一种混合模式,它可以被看作是 relativefixed 定位的结合。元素在页面滚动到某个阈值之前会表现得像是 relative 定位,滚动到这个阈值之后,元素就会固定在设定的位置。

在 TailwindCSS 中,sticky 对应的类就是 sticky,通常还需要配合 top, bottom, left 或者 right 使用,以确定元素变为 fixed 时的具体位置。

例子

如果我们想要创建一个当用户向下滚动页面时,会固定在距离视口顶部20像素的位置的侧边栏:

html
<div class="sticky top-20"> <!-- 侧边栏的内容 --> </div>

在这个例子中,top-20 是一个辅助类,用来设置滚动到离视口顶部20像素时元素变为 fixed 的位置。元素默认是 relative 定位,当页面滚动到元素的顶部边缘接近视口顶部20像素时,元素就会固定在那里。

总的来说,fixedsticky 定位是两种常用的CSS定位方法,它们在TailwindCSS中通过相应的实用类很容易实现。使用这些类可以帮助我们快速构建具有固定或粘性定位的用户界面元素。

2024年6月29日 12:07 回复
Header
Content
Footer

Class justify-between is not required, but I would leave him (for other case).

So, play with h-screen and mb-auto classes.

And you get this UI:

enter image description here

2024年6月29日 12:07 回复

Another approach would be using flex-grow.

shell
<link href="https://cdnjs.cloudflare.com/ajax/libs/tailwindcss/2.0.2/tailwind.min.css" rel="stylesheet"/> <div class="flex flex-col h-screen"> <div class="bg-red-500">header</div> <div class="bg-green-500 flex-grow">content</div> <div class="bg-blue-500">footer</div> </div>

Run code snippetHide results

Expand snippet

2024年6月29日 12:07 回复

New solution in 2022. Tailwindcss version 3.0.24 in codepen demo.

shell
<div class="min-h-screen"> <div>Content</div> <div class="sticky top-[100vh]">Footer</div> </div>

codepen demo

2024年6月29日 12:07 回复

use 'fixed' instead of 'static'

class="fixed bottom-0"

2024年6月29日 12:07 回复

Another way that was recently discovered by Sílvio Rosa uses position: sticky + top: 100vh on the footer. The way to achieve this with TailWindCSS is...

shell
<html class="min-h-screen"> <body class="min-h-screen"> <header>Header</header> <main>Content</main> <footer class="sticky top-[100vh]">footer</footer> </body> </html>

You can read the full article on CSS Tricks here

2024年6月29日 12:07 回复

你的答案