如何用Fresh、TailwindCSS和daisyUI实现自适应链接布局的页脚?
问题
我使用Fresh、TailwindCSS和daisyUI组件构建一个小高度页脚,自定义后的代码如下:
import IconSphere from "https://deno.land/x/tabler_icons_tsx@0.0.5/tsx/sphere.tsx" import IconBrandFacebook from "https://deno.land/x/tabler_icons_tsx@0.0.5/tsx/brand-facebook.tsx" import IconBrandDiscord from "https://deno.land/x/tabler_icons_tsx@0.0.5/tsx/brand-discord.tsx" export default function Footer() { return ( <footer class="footer items-center p-4 bg-neutral text-neutral-content"> <aside class="items-center grid-flow-col gap-8"> <span class='text-2xl italic font-mono font-bold tracking-wide'>Trấn Kỳ</span> <a class="link link-hover">Trấn Kỳ là gì?</a> <a class="link link-hover">Lý do viết Trấn Kỳ</a> <a class="link link-hover">Kế hoạch phát triển Trấn Kỳ</a> <a class="link link-hover">Tích hợp Trấn Kỳ vào hệ thống của bạn</a> <a class="link link-hover">Các buổi đáp ứng nhu cầu tự học lập trình</a> </aside> <nav class="grid-flow-col gap-4 md:place-self-center md:justify-self-end"> <IconSphere class="w-6 h-6" /> <IconBrandDiscord class="w-6 h-6" /> <IconBrandFacebook class="w-6 h-6" /> </nav> </footer> ) }
当前遇到的显示问题:
- 大屏幕下:页脚内容横向排列,链接和品牌名布局整齐,显示正常
- 中等屏幕下:链接文本最多显示两行,布局无挤压,显示正常
- 小屏幕下:链接文本被挤压变形,布局错乱
- 尝试给
<aside>添加md:grid-flow-col md:gap-8类,结果小屏幕的布局样式延续到了中等和大屏幕,不符合预期
我想要实现的页脚布局效果:
- 所有链接尽可能并排显示,每个链接的文本最多显示两行
- 当空间无法满足并排布局时,链接自动每行显示一个
解决方案
可以通过Tailwind的弹性布局+文本截断特性实现自适应需求,修改代码如下:
import IconSphere from "https://deno.land/x/tabler_icons_tsx@0.0.5/tsx/sphere.tsx" import IconBrandFacebook from "https://deno.land/x/tabler_icons_tsx@0.0.5/tsx/brand-facebook.tsx" import IconBrandDiscord from "https://deno.land/x/tabler_icons_tsx@0.0.5/tsx/brand-discord.tsx" export default function Footer() { return ( <footer class="footer items-center p-4 bg-neutral text-neutral-content"> <aside class="items-center flex flex-wrap gap-4 md:gap-8"> <span class='text-2xl italic font-mono font-bold tracking-wide'>Trấn Kỳ</span> <a class="link link-hover max-h-10 line-clamp-2">Trấn Kỳ là gì?</a> <a class="link link-hover max-h-10 line-clamp-2">Lý do viết Trấn Kỳ</a> <a class="link link-hover max-h-10 line-clamp-2">Kế hoạch phát triển Trấn Kỳ</a> <a class="link link-hover max-h-10 line-clamp-2">Tích hợp Trấn Kỳ vào hệ thống của bạn</a> <a class="link link-hover max-h-10 line-clamp-2">Các buổi đáp ứng nhu cầu tự học lập trình</a> </aside> <nav class="grid-flow-col gap-4 md:place-self-center md:justify-self-end"> <IconSphere class="w-6 h-6" /> <IconBrandDiscord class="w-6 h-6" /> <IconBrandFacebook class="w-6 h-6" /> </nav> </footer> ) }
关键修改说明:
<aside>布局调整:- 用
flex flex-wrap替代grid-flow-col,让子元素在空间不足时自动换行,实现自适应排列 - 设置
gap-4作为小屏幕下的间距,md:gap-8保留中等及以上屏幕的原有间距
- 用
链接文本限制:
max-h-10:限制链接的最大高度,对应两行文本的高度(可根据实际字体大小微调)line-clamp-2:强制文本最多显示两行,超出部分自动截断(daisyUI集成的Tailwind默认已启用该插件)
修改后即可满足需求:
- 大屏幕和中等屏幕空间充足时,链接并排显示,文本最多两行
- 小屏幕空间不足时,链接自动每行显示一个,文本不会挤压变形
内容的提问来源于stack exchange,提问作者Ooker
相关产品推荐
相关产品推荐

