如何实现占满无固定高度body全高度的垂直线?
解决垂直线无法贯穿整个body高度的问题
方案1:垂直线随文档内容高度自适应
当你想要垂直线高度匹配整个文档的实际内容高度(滚动时线跟随文档),可以按以下方式修改CSS:
body { position: relative; /* 设置relative,让.lines相对于body定位 */ margin: 0; /* 清除body默认边距,避免线位置偏移 */ } .lines { background-color: #000; width: 20px; position: absolute; right: 50%; top: 0; bottom: 0; /* 用top和bottom替代height:100%,自动撑满body的全部高度 */ } .div1 { background-color: red; width: 500px; height: 500px; } .div2 { margin-top: 20px; background-color: blue; width: 500px; height: 500px; }
方案2:垂直线固定在视口中间
如果需要垂直线始终停留在浏览器视口的中间位置(页面滚动时线保持不动),只需修改.lines的定位方式:
.lines { background-color: #000; width: 20px; position: fixed; /* 固定定位,相对于视口 */ right: 50%; top: 0; bottom: 0; }
问题原因
你之前设置height:100%无效的核心原因:
- 绝对定位元素的
height:100%是相对于最近的非static定位父元素的高度。 - 默认情况下
body是static定位,此时.lines的参考是浏览器视口,height:100%只能覆盖视口高度,而非整个文档的内容高度。 - 使用
top:0+bottom:0可以让元素自动填充从顶部到底部的全部可用空间,结合body: relative就能匹配文档的实际高度。
内容的提问来源于stack exchange,提问作者Mohammad Vard
相关产品推荐
相关产品推荐

