css 布局的一个奇葩需求
本文将探讨一种独特的 css 布局需求,即实现子元素 box-2 的高度等于父元素 box-1 的高度,同时 box-2 宽度超出 box-1 并占满整个 body。
需求:
实现:
以下是一个简单且有效的实现:
<style> body { margin: 0; } .box-1 { position: relative; } .box-2 { width: 100vw; height: 100%; background-color: rgba(0, 0, 0, 0.2); position: absolute; } </style> <div class="box-1 container py-5"> <div class="box-2"></div> <div class="box-3"> 111 <br> 111 <br> 111 <br> 111 <br> 111 <br> </div> </div>
说明:
補充:
如果需要为 box-1 设置最大宽度,可以添加以下 css:
<style> .container { max-width: 1000px; margin: 0 auto; } .py-5 { padding: 0 5em; } </style>
这将限制 box-1 的宽度为 1000px,并水平居中。