如何用Div实现不同比例的交替布局?
实现交替左右布局的解决方案
嘿,我看你用float来实现这种左右交替的布局,但遇到了问题——这大概率是因为浮动元素脱离了文档流,外层的<div>没有被正确撑开,导致各个模块挤在了一起,没有形成独立的行。下面给你几种靠谱的解决办法:
方法1:修复浮动布局(添加清除浮动)
给每个包含浮动元素的外层容器添加清除浮动的样式,让容器能正确包裹住浮动的子元素。你可以给外层div加一个clearfix类,然后定义对应的CSS:
<style> .clearfix::after { content: ""; display: table; clear: both; } </style> <div class="clearfix"> <div style="float: left; width: 70%">I'm on the left</div> <div style="float: left; width: 30%"><img src="https://i.ibb.co/C7SNdjk/cimb-foundation-image.png" width="100%"></div> </div> <div class="clearfix"> <div style="float: left; width: 30%"><img src="https://i.ibb.co/C7SNdjk/cimb-foundation-image.png" width="100%"></div> <div style="float: left; width: 70%">I'm on the second on the left</div> </div> <div class="clearfix"> <div style="float: left; width: 70%">I'm on the left</div> <div style="float: left; width: 30%"><img src="https://i.ibb.co/C7SNdjk/cimb-foundation-image.png" width="100%"></div> </div>
这个clearfix伪元素会在容器末尾生成一个看不见的块级元素,把浮动的元素“托住”,让容器恢复正常的高度,每个模块就会独立成行了。
方法2:用Flexbox布局(更现代简洁)
现在更推荐用Flexbox来做这种布局,它不需要处理浮动的各种坑,代码更清晰,还能轻松实现垂直对齐等效果:
<style> .row { display: flex; margin-bottom: 1rem; /* 给每行加一点间距,可选 */ } .row .text-col { flex: 7; /* 占7份宽度 */ padding: 0 1rem; /* 可选,加内边距让内容不贴边 */ } .row .img-col { flex: 3; /* 占3份宽度 */ } .row .img-col img { width: 100%; height: auto; /* 保持图片比例 */ } </style> <div class="row"> <div class="text-col">I'm on the left</div> <div class="img-col"><img src="https://i.ibb.co/C7SNdjk/cimb-foundation-image.png"></div> </div> <div class="row"> <div class="img-col"><img src="https://i.ibb.co/C7SNdjk/cimb-foundation-image.png"></div> <div class="text-col">I'm on the second on the left</div> </div> <div class="row"> <div class="text-col">I'm on the left</div> <div class="img-col"><img src="https://i.ibb.co/C7SNdjk/cimb-foundation-image.png"></div> </div>
Flexbox的flex属性可以灵活控制列的宽度比例,而且默认会让子元素垂直居中,布局更稳定。
方法3:用Grid布局(适合更复杂的场景)
如果以后需要更复杂的网格布局,Grid也是个好选择,对于这种两行两列的交替布局,代码也很简洁:
<style> .row { display: grid; grid-template-columns: 70% 30%; gap: 1rem; /* 列之间的间距,可选 */ margin-bottom: 1rem; } .row.reverse { grid-template-columns: 30% 70%; } .row img { width: 100%; height: auto; } </style> <div class="row"> <div>I'm on the left</div> <div><img src="https://i.ibb.co/C7SNdjk/cimb-foundation-image.png"></div> </div> <div class="row reverse"> <div><img src="https://i.ibb.co/C7SNdjk/cimb-foundation-image.png"></div> <div>I'm on the second on the left</div> </div> <div class="row"> <div>I'm on the left</div> <div><img src="https://i.ibb.co/C7SNdjk/cimb-foundation-image.png"></div> </div>
给需要反向的行加个reverse类,就能轻松切换列的顺序,非常灵活。
内容的提问来源于stack exchange,提问作者hatched
相关产品推荐
相关产品推荐

