我需要一个列中的 div,如果其中有太多项目,该 div 就会变得可滚动,但出于某种原因,我找到解决方案的唯一方法是使用“height:0”,这对我来说没有意义,我想我理解休息,但这对我来说仍然是神秘的。也许这里有人可以向我解释我不明白的事情
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Bootstrap demo</title>
<link
href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"
rel="stylesheet"
integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH"
crossorigin="anonymous"
/>
</head>
<body>
<!-- Take whole viewport and put container for rows -->
<form class="vh-100 bg-danger container-fluid">
<!-- Apply padding inside the container (not overriding container-fluid) -->
<div class="p-2 h-100 d-flex flex-column gap-2">
<div class="row bg-black">Row 1</div>
<div class="row bg-black">Row 2</div>
<!-- Fill the remaining space in viewport -->
<div class="row gap-2 flex-grow-1">
<div class="col bg-black">Column 1</div>
<div class="col-6 bg-black d-flex flex-column">
<div>Column 2</div>
<!-- Why is height 0 needed here? -->
<div class="flex-grow-1 overflow-auto" style="height: 0">
<div style="height: 100px"></div>
<div style="height: 100px"></div>
<div style="height: 100px"></div>
<div style="height: 100px"></div>
<div style="height: 100px"></div>
<div style="height: 100px"></div>
<div style="height: 100px"></div>
<div style="height: 100px"></div>
<div style="height: 100px"></div>
<div style="height: 100px"></div>
<div style="height: 100px"></div>
<div style="height: 100px"></div>
<div style="height: 100px"></div>
<div style="height: 100px"></div>
<div style="height: 100px"></div>
<div style="height: 100px"></div>
<div style="height: 100px"></div>
<div style="height: 100px"></div>
<div style="height: 100px"></div>
<div style="height: 100px"></div>
<div style="height: 100px">test</div>
</div>
</div>
<div class="col bg-black">Column 3</div>
</div>
</div>
</form>
<script
src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"
integrity="sha384-YvpcrYf0tY3lHB60NNkmXc5s9fDVZLESaAA55NDzOxhy9GkcIdslK1eN7N6jIeHz"
crossorigin="anonymous"
></script>
</body>
</html>
通过使用高度:0,
您确保:
但是,如果您发现这太不直观了,还有另一种方法...通过设置父容器的 flex 属性,您将获得相同的效果,如下所示:
代码:
.flex-grow-1 {
flex: 1 1 auto; /* Flex-grow enabled, and height adapts to content */
overflow: auto;
}
这是 CSS Flexbox 布局中的常见模式。虽然 height: 0 可能看起来很奇怪,但它实际上是操纵可滚动内容的 Flexbox 行为的巧妙方法