首页 > 解决方案 > 当父 div 发生溢出时隐藏整个子 div

问题描述

我在一个固定的父 div 中有 5 个子 div,其高度因设备而异。如果它不适合固定的父 div,我正在寻找任何技巧来隐藏整个 div。

我试过“溢出:隐藏;” 但它只裁剪溢出的部分而不是整个div

.fixed-div {
            background: greenyellow;
            height: calc(100vh - 10px);
            width: 100px;
            position: fixed;
            overflow: hidden;
        }

        .child-div {
            width: 60px;
            height: 60px;
            background: red;
            margin: 20px auto;
        }
<div class="container">
        <div class="fixed-div">
            <div class="child-div">

            </div>
            <div class="child-div">

            </div>
            <div class="child-div">

            </div>
            <div class="child-div">

            </div>
            <div class="child-div">

            </div>
            <div class="child-div">

            </div>
            <div class="child-div">

            </div>
        </div>
    </div>

预期:如果高度只能容纳 2 个子 div,则不应完全显示或裁剪其他 5 个子 div

标签: htmlcss

解决方案


这可以使用 CSS 网格来完成,通过定义最大宽度和动态行数,以及定义溢出:隐藏以隐藏没有空间的项目。看看这个:

.fixed-div {
	display: grid;
	grid-template-rows: repeat( auto-fit, minmax(100px, 1fr));
	grid-template-columns: 100px;
	grid-auto-flow: column;
    background: greenyellow;
    max-height: calc(100vh - 10px);
	max-width: 100px;
	overflow: hidden;
}

.child-div {
    width: 60px;
    height: 60px;
    background: red;
    margin: 20px auto;
}
<div class="fixed-div">
            <div class="child-div">

            </div>
            <div class="child-div">

            </div>
            <div class="child-div">

            </div>
            <div class="child-div">

            </div>
            <div class="child-div">

            </div>
            <div class="child-div">

            </div>
            <div class="child-div">

            </div>
        </div>


推荐阅读