如何使用CSS Grid/Flex实现支持双视图切换的不同行高UI
实现双布局切换方案
问题原因
你之前的Grid实现出现间隙的核心原因是未指定元素的跨行/列规则,Grid默认每个元素独占一行,第一行同时放置a和c时,行高会匹配更高的c元素,导致a下方出现多余空白,b落到第二行自然就和a拉开了大间隙。
方案1:CSS Grid实现(更推荐,适配动态高度场景)
无需修改DOM结构,仅通过切换容器类即可实现两种布局,代码如下:
CSS代码
.a { width: 50px; height: 30px; background: pink; } .b { width: 50px; height: 80px; background: green; } .c { width: 50px; height: 80px; background: red; } .cont { display: grid; column-gap: 20px; /* 两列之间的间距可自行调整 */ width: 120px; } /* 两列布局类 */ .cont.two-col { grid-template-columns: 50px 50px; } .cont.two-col .a { grid-row: 1 / 2; grid-column: 1 / 2; } .cont.two-col .b { grid-row: 2 / 3; grid-column: 1 / 2; } .cont.two-col .c { grid-row: 1 / 3; /* 跨两行占满第二列高度 */ grid-column: 2 / 3; } /* 单列布局类 */ .cont.one-col { grid-template-columns: 1fr; } .cont.one-col .a { order: 1; } .cont.one-col .c { order: 2; grid-row: unset; /* 取消跨行规则 */ grid-column: unset; } .cont.one-col .b { order: 3; }
HTML结构
<!-- 切换布局只需修改cont的类为two-col/one-col即可 --> <div class="cont one-col"> <div class="a">A</div> <div class="c">C</div> <div class="b">B</div> </div>
方案2:Flex实现
适合元素高度固定的场景,代码如下:
.a { width: 50px; height: 30px; background: pink; } .b { width: 50px; height: 80px; background: green; } .c { width: 50px; height: 80px; background: red; } .cont { display: flex; flex-direction: column; flex-wrap: wrap; width: 120px; } /* 两列布局类 */ .cont.two-col { height: 110px; /* 高度等于a+b的总高度,刚好容纳两个元素在左列 */ } .cont.two-col .c { margin-left: 20px; /* 两列间距可调整 */ } /* 单列布局类 */ .cont.one-col { height: auto; } .cont.one-col .a { order: 1; } .cont.one-col .c { order: 2; margin-left: 0; } .cont.one-col .b { order: 3; }

内容的提问来源于stack exchange,提问作者ToughCookie
相关产品推荐
相关产品推荐

