position

2020-07-19  本文已影响0人  darkTi

一、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(粘性定位)

<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处(当然你得保证父容器的高度足以让每一条内容都滚到顶部,否则父容器不够高,还没滚到头呢,就停住了)

上一篇 下一篇

猜你喜欢

热点阅读