使用position:absolute;bottom:0时菜单固定到屏幕底部而非父元素的问题
解决绝对定位菜单栏未固定到父级底部的问题
嘿,这个问题我之前踩过坑!核心原因是CSS绝对定位的参照规则在搞鬼:当你给元素设置position: absolute时,它会去找最近的、不是默认static定位的祖先元素作为参照点。如果所有祖先都是默认的static(比如你的#header就是默认值),那它就会直接相对于浏览器视口来定位,所以才会跑到屏幕底部去。
解决步骤超简单:
给你的父元素#header加上position: relative;就行,这样#menu就会把#header当成定位参照,bottom: 0就会乖乖贴在#header的底部了。
修改后的完整代码:
* { font-family: Arial, sans-serif; border: 0 solid black; box-sizing: border-box; } body { margin: 0; padding: 0; height: 500px; /*for testing*/ background-color: #00FF00; } #header { height: 270px; border: 1px solid #FF0000; position: relative; /* 关键新增代码 */ } #menu { display: block; height: 50px; position: absolute; bottom: 0; width: 100%; /* 可选:让菜单栏铺满父级宽度 */ background-color: #333; /* 加个背景方便看效果 */ color: white; }
补充小提示:
- 加上
width: 100%是因为绝对定位的元素默认宽度是内容宽度,加上它可以让菜单栏和#header同宽,视觉上更完整。 position: relative不会改变父元素的正常布局,只是给内部的绝对定位元素提供一个参照容器,完全不影响其他布局。
内容的提问来源于stack exchange,提问作者wohe1
相关产品推荐
相关产品推荐

