如何让menu div固定在页面底部(滚动时保持固定)
如何将菜单固定在页面底部(滚动时保持固定)
需求说明
需要将class为menu的div固定在页面底部,即使页面滚动也保持固定状态。现有代码如下:
原CSS代码
.overflow{ width: 100%; height: 100%; background-color: rgba(0, 0, 0, 0.2); position: absolute; inset: 0px; display: block; } .menu{ display: flex; flex-direction: column; position: relative; margin-top: auto; background-color: white; border-radius: 12px 12px 0px 0px; max-height: 90%; transform: translateY(0px); transition: transform 250ms ease-out 0s; }
原HTML代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <div class="overflow"> </div> <div class='menu'> <h1>item 1 </h1> <h1>item 1 </h1> </div> </body> </html>
实现方案
只需修改.menu的CSS定位属性,核心调整如下:
修改后的.menu CSS代码
.menu{ display: flex; flex-direction: column; position: fixed; /* 改为固定定位,相对于浏览器视口 */ bottom: 0; /* 将菜单固定在页面底部 */ left: 0; right: 0; /* 左右贴边,铺满整个视口宽度 */ background-color: white; border-radius: 12px 12px 0px 0px; max-height: 90%; transform: translateY(0px); transition: transform 250ms ease-out 0s; z-index: 1; /* 确保菜单显示在遮罩层上方 */ }
关键修改点解释
position: fixed:让元素脱离文档流,始终相对于浏览器视口固定,不会随页面滚动移动bottom: 0:将菜单的底边与视口底部对齐,实现底部固定效果left: 0+right: 0:使菜单宽度自动铺满整个视口(如果需要固定宽度,可替换为width: 100%或具体数值)z-index: 1:由于.overflow是全屏遮罩层(absolute定位),设置更高的z-index可以确保菜单不会被遮罩挡住
HTML代码无需修改,保持原样即可。
内容的提问来源于stack exchange,提问作者sPEER PANSER
相关产品推荐
相关产品推荐

