CSS绝对定位width100%超出容器问题?

//html
body>footer
// css
body {
    position: relative;
    margin: 0 auto;
    max-height: 500px;
}
footer {
    position: fixed;
    width: 100%;
}

footer会超出body直到浏览器边缘,如何解决?
前提是不能直接设footer的宽度

阅读 13.7k
8 个回答

fixed是相对于浏览器窗口进行定位,absolute才是相对于 static 定位以外的第一个父元素进行定位,所以改成absolute就可以了

首先 fixed是根据视窗来进行定位的,所以没有出现你想要的继承body的宽度情况出现。
不过根据你的代码来看你是做的移动端的页面,那footer应该是个菜单栏,需要固定在底部

解决思路:
1. js获取body实际宽度,然后再给footer赋值宽度。
2. body和footer都采用百分比布局或者flex布局。

把footer设置成position:absolute .......

* {
    margin:0;
    padding:0;
}

这个加上去,试一下

你至少给body一个宽度,width:100%呀

html,body{width:100%}

//html
body>footer
// css
body {

position: relative;
margin: 0 auto;
max-height: 500px;
width:100%;

}
footer {

position: fixed;
width: 100%;
padding:0;
margin:0;

}

原因: fixed固定布局是基于视窗的,跟父元素无关,因此会超出容器

解决: 只能设宽度了。保持fixed的情况下,要加上与body相同的max-width。考虑到要共用的问题,可以分为两种情况:不用预处理器,可以存为一个公共class,所有页面共用;用预处理器,就存为变量了,更简单。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题