html - 如何制作固定位置的页眉?

标签 html css

当top等于0%时,header的位置是否可以固定?~ 例如,标题顶部值从 20% 开始,我们向下滚动,它达到 0% 的值,然后保持固定。

我只能使用 HTML/CSS。

最佳答案

是的,这可以通过新提议的属性 position: sticky; 目前仅在 Firefox 中受支持并在 Safari 中作为前缀来实现。参见 Caniuse有关浏览器支持的更多信息。

来自W3C :

A stickily positioned box is positioned similarly to a relatively positioned box, but the offset is computed with reference to the nearest ancestor with a scrolling box, or the viewport if no ancestor has a scrolling box.

Specifically, once a box has been laid out according to the normal flow or floated, its sticky offset is computed as described below. Offsetting a box (B1) in this way has no effect on the box (B2) that follows: B2 is given a position as if B1 were not offset and B2 is not re-positioned after B1’s offset is applied. This implies that sticky positioning may cause boxes to overlap. However, if sticky positioning causes an 'overflow: auto' or 'overflow: scroll' box to have overflow, the user agent must allow the user to access this content (at its offset position), which, through the creation of a scrolling mechanism, may affect layout.

JSFiddle Example

html, body {
    margin: 0;
}

body * {
    margin: 20px;
    padding: 20px;
}

.header {
    margin: 0;
    padding: 20px;
    background: #000;
}

.header span {
    display: block;
    color: #fff;
    margin: 0 auto;
    text-align: center;
    padding: 0;
}

.placeholder {
    border: 1px solid black;
    margin: 0 auto;
    text-align: center;
    height: 300px;
}

.slider {
    background: #006264;
    color: white;
    font-weight: bold;
    margin: 0 auto;
    position: sticky;
    top: 0px;
}
<div class="header"><span>This is a header</span></div>
<div class="placeholder">This div holds place</div>
<div class="slider">This should slide up and then stick.</div>
<div class="placeholder">This div holds place</div>
<div class="placeholder">This div holds place</div>
<div class="placeholder">This div holds place</div>
<div class="placeholder">This div holds place</div>

关于html - 如何制作固定位置的页眉?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27819858/

相关文章:

javascript - jQuery 交换元素内容给出类型 F 错误

javascript - document.querySelector 获取包含括号的类名

javascript - 自动完成动态创建的输入

html - HTA - 验证条目

javascript - 如何使用 JavaScript 检测文档中是否存在 HTML5 有效文档类型?

html - 我无法让我的内容在右框中垂直居中

javascript - 使用空格更新 contenteditable DIV

php - 如何获得以像素为单位的固定宽度的完整单词的子字符串

html - 将 Bootstrap 从 3.3.4 升级到 4.0

html - Safari 桌面中奇怪的 iframe 滚动行为