position

作者: darkTi | 来源:发表于2020-07-19 18:33 被阅读0次

一、position的值

  1. static(静态定位)
    在标准文档流中,不会脱离文档流,top, right, bottom, left 等属性失效
  2. relative(相对定位)
    在标准文档流中,不会脱离文档流,依赖top, right, bottom, left 等属性设置该对象的偏移位置,相对于它的父元素进行相对定位,同时可通过z-index定义层叠关系。
  3. absolute(绝对定位)
    会脱离文档流,依赖top, right, bottom, left 等属性设置偏移位置,相对于离它最近的非static定位的定位元素(relative、absolute都可,见下面例子),同时也可通过z-index定义层叠关系。
  4. fixed(固定定位)
    会脱离文档流,依赖top, right, bottom, left 等属性设置该对象相对于浏览器窗口的的偏移位置,同时也可通过z-index定义层叠关系。
  5. sticky(粘性定位)
    不会脱离文档流

二、absolute(绝对定位)

<div class="yeye">
  <div class="baba">
    爸爸
    <div class="erzi">
      儿子
      <div class="sunzi">孙子</div>
    </div>
  </div> 
</div>
.yeye{
  width:300px;
  height:300px;
  border:1px solid red;
}
.baba{
   width:200px;
  height:200px;
  border:1px solid #09c;
  position:relative;
}
.erzi{
   width:150px;
  height:150px;
  border:1px solid green;
  position:absolute;
  top:100%;
}
.sunzi{
  width:100px;
  height:100px;
  border:2px solid black;
  position:absolute;
  top
image.png

孙子相对于儿子绝对定位,儿子相对于爸爸绝对定位;

三、sticky(粘性定位)

  • 首先它是不会脱离文档流的,sticky,顾名思义,它是粘在页面的某一处;直接上例子:
<div class="container">
    <nav>我是导航栏</nav>
    <div class="content">
        <p>我是内容栏</p>
        <p>我是内容栏</p>
        <p>我是内容栏</p>
        <p>我是内容栏</p>
        <p>我是内容栏</p>
        <p>我是内容栏</p>
        <p>我是内容栏</p>
        <p>我是内容栏</p>
    </div>
</div>
.container{
  width:300px;
  height:1000px;
  background:#ccc;
  margin:0 auto;
}
nav{
  background:#09c;
  height:50px;
  position:sticky;
  top:0;
}
.content{
  margin-top:30px;
  background:#90c;
}
p{
  text-align:center;
  margin-bottom:20px;
}
原始模样.png
滑动滚动条.png

可见导航栏是黏在top:0处的;再来看一个:

<div class="container">
    <div class="list">内容</div>
    <div class="list">内容</div>
    <div class="list">内容</div>
    <div class="list">内容</div>
    <div class="list">内容</div>
</div>
.container{
  width:300px;
  height:1000px;
  background:#ccc;
  margin:0 auto;
  display:flow-root; //变成BFC,防止margin合并
}
.list{
  width:100%;
  height:40px;
  background:#90c;
  margin:30px 0;
  text-align:center;
  line-height:40px;
  position:sticky;
  top:0;
} 
原本模样.png
滑动滚动条.png

可见滑动滚动条时,每一条内容最终都会固定到top:0处(当然你得保证父容器的高度足以让每一条内容都滚到顶部,否则父容器不够高,还没滚到头呢,就停住了)

  • 总结
    ①须指定 top, right, bottom 或 left 四个阈值其中之一,才可使粘性定位生效。否则其行为与相对定位相同。并且 top 和 bottom 同时设置时,top 生效的优先级高,left 和 right 同时设置时,left 的优先级高。(当然最常用的就是top,用来设置导航栏)
    ②设置position:sticky元素的父元素的overflow一定不能是hidden或者auto,一定保证父元素足够高,能够进行滚动,否则你设置的position:sticky也没有意义了;
    ③如果 position:sticky 元素的任意父节点定位设置为position:relative | absolute | fixed,则元素相对父元素进行定位,而不会相对 viewprot 定位;
    ④然而它的兼容性很不好。。。

相关文章

网友评论

      本文标题:position

      本文链接:https://www.haomeiwen.com/subject/vtxhwqtx.html