lock an element to the browser window with fixed positioning - zilongxuan001/LearnFreecode GitHub Wiki

使用固定位置锁定一个元素到它的浏览器窗口

理解

CSS偏移提供的另一个布局方法是固定位置(fixed position),是一种绝对的定位,可以把元素相对的锁定在浏览器窗口上。

类似绝对定位(absolute position),固定位置被用于CSS偏移,同样也是从文档的自然流中移除。其他的条目(item)不会认识到它的位置。

fixedabsolute一个关键的区别就是当用户上下滚动浏览时,fixed position不会移动,也即是说,被固定的元素会始终出现在浏览器窗口里。

练习

代码里导航栏被narbar的id标记了,改变其positionfixed,设置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>

来源

Applied Visual Design: Lock an Element to the Browser Window with Fixed Positioning | Learn freeCodeCamp

CHANGELOG

2018-10-23 17:35:56

⚠️ **GitHub.com Fallback** ⚠️