是否建议在 html 标签上使用 position: relative?
Is using position: relative on html tag advised?
我刚刚找到了创建粘性页脚的解决方案:
html {
position: relative;
}
#footer {
position: absolute;
bottom: 0;
left: 0; right: 0;
}
尽管我想知道将 position:relative
放在 html
标签上有何建议。
我的理解是:position: absolute
不是相对于视口,而是相对于文档。
这是好的做法吗?
虽然根元素 html
可以像任何其他元素一样由 CSS 设置样式,但由于它是根元素,某些属性的行为可能会有所不同。 position
是这些属性之一:特别是 spec 有这样的话:
User agents may treat position as 'static' on the root element.
据我所知,没有现代浏览器 实际上 这样做,但仍然不能保证 position: relative
将始终在根元素上工作。在您的情况下,您可以通过在 body
元素而不是 html
元素上设置 position: relative
来简单地避免这种情况:
body {
position: relative;
}
#footer {
position: absolute;
bottom: 0;
left: 0; right: 0;
}
请注意,如果正文没有达到视口的高度(例如,当页面中没有足够的内容时),页脚将不会粘在页面底部。如果这对您来说是个问题,请按照我的回答 here:
中的说明在 html
和 body
上设置 height
和 min-height
html {
height: 100%;
}
body {
position: relative;
min-height: 100%;
}
#footer {
position: absolute;
bottom: 0;
left: 0; right: 0;
}
我刚刚找到了创建粘性页脚的解决方案:
html {
position: relative;
}
#footer {
position: absolute;
bottom: 0;
left: 0; right: 0;
}
尽管我想知道将 position:relative
放在 html
标签上有何建议。
我的理解是:position: absolute
不是相对于视口,而是相对于文档。
这是好的做法吗?
虽然根元素 html
可以像任何其他元素一样由 CSS 设置样式,但由于它是根元素,某些属性的行为可能会有所不同。 position
是这些属性之一:特别是 spec 有这样的话:
User agents may treat position as 'static' on the root element.
据我所知,没有现代浏览器 实际上 这样做,但仍然不能保证 position: relative
将始终在根元素上工作。在您的情况下,您可以通过在 body
元素而不是 html
元素上设置 position: relative
来简单地避免这种情况:
body {
position: relative;
}
#footer {
position: absolute;
bottom: 0;
left: 0; right: 0;
}
请注意,如果正文没有达到视口的高度(例如,当页面中没有足够的内容时),页脚将不会粘在页面底部。如果这对您来说是个问题,请按照我的回答 here:
中的说明在html
和 body
上设置 height
和 min-height
html {
height: 100%;
}
body {
position: relative;
min-height: 100%;
}
#footer {
position: absolute;
bottom: 0;
left: 0; right: 0;
}