lock an element to the browser window with fixed positioning - zilongxuan001/LearnFreecode GitHub Wiki
CSS偏移提供的另一个布局方法是固定位置(fixed position
),是一种绝对的定位,可以把元素相对的锁定在浏览器窗口上。
类似绝对定位(absolute position
),固定位置被用于CSS偏移,同样也是从文档的自然流中移除。其他的条目(item
)不会认识到它的位置。
fixed
和absolute
一个关键的区别就是当用户上下滚动浏览时,fixed position
不会移动,也即是说,被固定的元素会始终出现在浏览器窗口里。
代码里导航栏被narbar
的id标记了,改变其position
为fixed
,设置top
偏移为0px, left
偏移为0px。
注意h1
位置的影响,它不会被推下来来容纳导航栏,而需要被分别的调整开。
<style>
#navbar {
position: fixed;
top: 0px;
left: 0px;
width: 100%;
background-color: #767676;
}
nav ul {
margin: 0px;
padding: 5px 0px 5px 30px;
}
nav li {
display: inline;
margin-right: 20px;
}
a {
text-decoration: none;
}
</style>
<body>
<header>
<h1>Welcome!</h1>
<nav id="navbar">
<ul>
<li><a href="">Home</a></li>
<li><a href="">Contact</a></li>
</ul>
</nav>
</header>
<p>I shift up when the #navbar is fixed to the browser window.</p>
</body>
2018-10-23 17:35:56