如何实现div文本框固定在导航栏下、内容溢出可滚动且缩放时位置不变
样式修复与需求实现代码
需要修改的CSS规则
直接替换原有CSS中对应的部分即可:
/* 先修改body规则,避免内容被固定导航栏遮挡 */ body { font-family: "Poppins"; padding-top: 50px; /* 匹配导航栏高度 */ } /* 背景层调整,保证背景固定不跟随滚动 */ .background { background: linear-gradient( to bottom left, rgba(0, 0, 0, 0.7), rgba(255, 255, 255, 0.4) ), url(./Revendreth111.jpg); position: fixed; top: 0; left: 0; z-index: -1; /* 放到最底层 */ width: 100%; height: 100vh; background-position: center; background-repeat: no-repeat; background-size: cover; background-attachment: fixed; } /* 替换原有.text-box的全部规则 */ .text-box { background: rgba(12, 12, 12, 0.555); color: rgb(161, 161, 161); position: fixed; top: 50px; /* 固定在导航栏正下方 */ left: 50%; transform: translateX(-50%); /* 水平居中,窗口缩放也不会偏移 */ width: 70%; min-width: 320px; /* 最小宽度限制,文字不会过度挤压 */ max-height: calc(100vh - 70px); /* 最大高度适配屏幕,超出就滚动 */ overflow-y: auto; /* 内容超出时纵向滚动 */ margin-left: auto; margin-right: auto; padding: 20px; filter: drop-shadow(0 0.2rem 0.9rem rgba(0, 0, 0, 0.418)); backdrop-filter: blur(0.11rem); } /* 新增小屏幕适配规则 */ @media screen and (max-width: 768px) { .row { flex-direction: column; } .column, #sidebar { flex: 100%; width: 100%; margin-left: 0; margin-bottom: 20px; } .text-box { width: 95%; } }
功能说明
- text-box会固定在导航栏下方,水平居中,调整窗口大小也不会出现位置偏移
- 内部内容超过屏幕高度时自动出现纵向滚动条,不需要修改现有HTML结构
- 宽度设了最小320px的限制,小于该宽度时才会出现横向滚动,保证文字可读性
- 小屏幕下两列布局自动切换为单列,适配移动端显示
内容的提问来源于stack exchange,提问作者Mizantropija
相关产品推荐
相关产品推荐

