You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让<figure>元素始终在视口中可见(Tailwind+daisyUI场景)

问题:figure元素在低视口高度下无法完整显示且保持比例

我使用Tailwind和daisyUI组件库设计了一个双区块页面:左侧是文本与按钮,右侧是带标题的<figure>元素。预期整个<figure>始终在视口中可见且保持比例,但视口高度较低时显示异常,尝试多种Max-Height类均无效。

原代码如下:

<div class="flex flex-col md:flex-row bg-green-300 items-center max-w-none space-x-10 px-10 h-screen">
  <section class="align-middle justify-center">
    <article class="prose py-10">
      <h1>404 – Không tìm thấy trang</h1>
      <p>
        Liên kết rút gọn với đuôi <code>{đuôiRútGọn}</code>{" "}
        chưa từng được tạo hoặc đã bị xoá trên hệ thống. Liên hệ người gửi liên kết cho bạn để được hỗ trợ.
      </p>
    </article>
    <button class="btn">
      <a href="/">Tạo liên kết khác</a>
    </button>
  </section>
  <section class="align-middle">
    <figure class="max-h-fit">
      <img src="https://placehold.co/2048x1488" alt="Tranh vẽ hai nguời đang trò chuyện với nhau ở quán nước vỉa hè" />
      <figcaption>
        Tranh: <a class="prose" href="https://doi-thoai.deno.dev/TheLinhRab.doi-thoai.1">Linh Rab</a>
      </figcaption>
    </figure>
  </section>
</div>
解决方案

通过调整布局结构和元素的高度约束,确保figure在任何视口高度下都能完整显示并保持比例:

修改后的代码:

<div class="flex flex-col md:flex-row bg-green-300 items-center max-w-none px-10 min-h-screen overflow-hidden">
  <section class="flex-1 flex flex-col justify-center py-10">
    <article class="prose">
      <h1>404 – Không tìm thấy trang</h1>
      <p>
        Liên kết rút gọn với đuôi <code>{đuôiRútGọn}</code>{" "}
        chưa từng được tạo hoặc đã bị xoá trên hệ thống. Liên hệ người gửi liên kết cho bạn để được hỗ trợ.
      </p>
    </article>
    <button class="btn mt-4">
      <a href="/">Tạo liên kết khác</a>
    </button>
  </section>
  <section class="flex-1 flex flex-col justify-center items-center py-10">
    <figure class="max-h-[calc(100vh-4rem)] w-full flex flex-col items-center">
      <img 
        src="https://placehold.co/2048x1488" 
        alt="Tranh vẽ hai nguời đang trò chuyện với nhau ở quán nước vỉa hè" 
        class="max-w-full max-h-[calc(100vh-8rem)] object-contain"
      />
      <figcaption class="mt-2">
        Tranh: <a class="prose" href="https://doi-thoai.deno.dev/TheLinhRab.doi-thoai.1">Linh Rab</a>
      </figcaption>
    </figure>
  </section>
</div>

关键修改说明:

  • 父容器:将h-screen替换为min-h-screen确保至少占满视口高度,添加overflow-hidden避免内容溢出;移除space-x-10,改用左右区块的py-10控制垂直间距
  • 左右区块:添加flex-1让两个区块平分可用宽度,同时用flex flex-col justify-center让区块内的内容垂直居中
  • figure元素:设置max-h-[calc(100vh-4rem)],通过计算减去上下内边距高度,确保整个figure不会超出视口范围
  • 图片:使用max-w-full max-h-[calc(100vh-8rem)]限制最大高度(额外减去figcaption的高度),搭配object-contain保证图片比例不变且完整显示

内容的提问来源于stack exchange,提问作者Ooker

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 17:25:15