为带固定头部的页面添加匹配视口高度的滚动条
解决方案
你的问题出在content元素同时设置了margin-top:8rem和height:100vh,导致内容总高度超出视口(100vh + 8rem),滚动条自然会溢出。下面是几种靠谱的修复方案:
方案1:使用calc计算剩余高度
直接调整wrapper和content的样式,让wrapper占据头部之外的所有视口高度,滚动条仅在wrapper内生效:
<template> <Header /> <!-- 固定定位,高度8rem --> <div class="wrapper"> <div class="content"> <!-- 你的内容 --> </div> </div> </template> <style scoped> .wrapper { max-height: calc(100vh - 8rem); overflow-y: auto; /* 可选:避免内容贴边 */ padding-top: 1rem; } .content { /* 移除多余的margin-top和height设置 */ } </style>
方案2:用CSS变量维护头部高度(更易维护)
如果头部高度可能变化,用CSS变量统一管理,后续修改只需改一处:
<template> <Header /> <div class="wrapper"> <div class="content"> <!-- 你的内容 --> </div> </div> </template> <style> /* 全局定义变量 */ :root { --header-height: 8rem; } </style> <style scoped> /* 头部组件内也可复用这个变量 */ /* .header { position: fixed; height: var(--header-height); width: 100%; top: 0; } */ .wrapper { max-height: calc(100vh - var(--header-height)); overflow-y: auto; margin-top: var(--header-height); /* 避免内容被头部遮挡 */ } .content { /* 无需额外高度设置 */ } </style>
方案3:Flex布局(最简洁)
利用flex的自动分配空间特性,让body作为容器,自动分配头部和内容区的高度:
<template> <Header /> <div class="wrapper"> <div class="content"> <!-- 你的内容 --> </div> </div> </template> <style> body { margin: 0; display: flex; flex-direction: column; min-height: 100vh; } </style> <style scoped> .header { position: fixed; /* 如果头部需要固定在顶部,保留这个属性 */ width: 100%; height: 8rem; } .wrapper { flex: 1; margin-top: 8rem; /* 避开固定头部 */ overflow-y: auto; } .content { /* 无需额外高度设置 */ } </style>
注意:如果头部是固定定位(fixed),一定要给wrapper加上margin-top:8rem,避免内容被头部遮挡。以上方案都能自动适配窗口Resize,不需要额外写JS逻辑。
内容的提问来源于stack exchange,提问作者Cuberino
相关产品推荐
相关产品推荐

