如何在不重复使用`flex flex-col flex-1 Overflow-hidden`的情况下使嵌套元素可滚动?

问题描述 投票:0回答:1

我正在使用 Tailwind CSS 创建 UI。为简单起见,假设 UI 如下所示:

<div class="h-full">
    <div> <p> Some text </p> </div>
    <div> <button> Click me </button> </div>
    <form>
        <input>
        <div>text</div>
        <div>text</div>
        <div>
            <div> more text </div>
            <div> <!-- I want this <div> to scroll through the content -->
                <div class="h-[2000px]"> Alot of content overflowing the screen! </div>
            </div>
        </div>
    </form>
</div>

所有这些元素都放置在垂直流中。带有

div
h-[2000px]
深深嵌套在我的 UI 中,由于其大小,我想让父级
div
滚动浏览大
div
。我很难完成这项工作,但最终找到了这个解决方案:

<div class="h-full flex flex-col">
    <div> <p> Some text </p> </div>
    <div> <button> Click me </button> </div>
    <form class="flex flex-col flex-1 overflow-hidden">
        <input>
        <div>text</div>
        <div>text</div>
        <div class="flex flex-col flex-1 overflow-hidden">
            <div> more text </div>
            <div class="flex flex-1 overflow-auto">
                <div class="h-[2000px]"> Alot of content overflowing the screen! </div>
            </div>
        </div>
    </form>
</div>

我必须在元素的每个嵌套层上设置类

flex flex-col flex-1 overflow-hidden
,并且为了使嵌套的 div 可滚动,我必须设置
flex flex-col flex-1 overflow-auto
。在这个例子中,大元素嵌套得不是那么深,但在我的真实案例场景中,我写了
flex flex-col flex-1 overflow-hidden
大约 5 次。这最终变得很难追踪......

是否有更简单的方法可以使深度嵌套在 DOM 中的大元素可滚动?

css tailwind-css
1个回答
0
投票

这是我的方法:

<body>
  <main class="max-h-screen bg-green-200">
    <div><p>Some text</p></div>
    <div><button>Click me</button></div>
    <form>
      <input />
      <div>text</div>
      <div>text</div>
      <div>
        <div>more text</div>
        <div class="max-h-48 overflow-y-scroll">
          <div class="h-[2000px] bg-red-200">Alot of content overflowing the screen!</div>
        </div>
      </div>
    </form>
    <div class="h-[2000px] bg-purple-200">Another content that will overflow main as usual!</div>
  </main>
</body>

但这需要你设置一个溢出高度(在我的例子中是

max-h-48
)。

我知道您希望 div 溢出到页面末尾。在这种情况下,我会这样做以避免太多的弹性组件:

<body>
  <main class="h-screen overflow-hidden">
    <div><p>Some text</p></div>
    <div><button>Click me</button></div>
    <form class="h-full">
      <input />
      <div>text</div>
      <div>text</div>
      <div class="h-full">
        <div>more text</div>
        <div class="h-full overflow-y-scroll">
          <div class="h-[2000px] bg-red-200">Alot of content overflowing the screen!</div>
        </div>
      </div>
    </form>
  </main>
</body>
© www.soinside.com 2019 - 2024. All rights reserved.