定位属性position,相对定位,绝对定位

在CSS中关于定位的内容是:

position:relative | absolute | static | fixed

• static 自动定位,自动定位就是元素在页面普通文档流中由HTML自动定位,普通文档里中的元素也称为流动元素。不能通过z-index进行层次分级。

• relative 相对定位,相对定位不脱离文档流,参考其在原来文档流中的位置,通过 top,bottom,left,right 定位,并且可以通过z-index进行层次分级。

• absolute 绝对定位,绝对定位脱离文档流,依据最近的已经定位(绝对、相对或固定定位)的父元素,通过 top,bottom,left,right 定位。当父级 position 为 static 时,absolute元素将依据body根元素(浏览器窗口)进行定 位,可以通过z-index进行层次分级。

• fixed 固定定位,固定定位与父元素无关(无论父元素是否定位),直接根据浏览器窗口定位,且不随滚动条拖动 页面而滚动,可通过z-index进行层次分级。

 1 <template>
 2   <div class="home">
 3     <div class="box box1">我是box1 position: fixed; 相对于浏览器发生移动</div>
 4     <div class="box box2">
 5       <div class="right-top">我是box2-1  position: absolute; 如果父级就是自身 相对于body左上角作为参考定位发生移动  </div>
 6       <div class="right-bottom">我是box2-2</div>
 7     </div>
 8     <div class="box box3">我是box3</div>
 9     <div class="box box4">我是box4  position: relative; 相对于自身的位置发生移动</div>
10   </div>
11       
12 </template>
13 <style lang="scss" scoped>
14 .home{
15   width: 100%;
16   background: burlywood;
17   color: aliceblue;
18   .box{
19     width: 50%;
20     height: 1rem;
21   }
22   .box1{
23     background: powderblue;
24     position: fixed;
25     top:0.5rem;
26     right: 0;
27   }
28   .box2{
29     background: pink;
30     position: absolute;
31     top:0.2rem;
32     left:0.1rem;
33   }
34   .box3{
35     background: yellow;
36   }
37   .box4{
38     background: plum;
39     position: relative;
40     top:0.2rem;
41   }
42 }

<template>
  <div class="home">
    <div class="box box1">我是box1</div>
    <div class="box box2">
      <div class="right-top">我是box2-1</div>
      <div class="right-bottom">我是box2-2</div>
    </div>
    <div class="box box3">我是box3</div>
    <div class="box box4">我是box4</div>
  </div>
      
</template>
<style lang="scss" scoped>
.home{
  width: 100%;
  background: burlywood;
  color: aliceblue;
  .box{
    width: 50%;
    height: 1rem;
  }
  .box1{
    background: powderblue;
  }
  .box2{
    background: pink;
    position: relative;
    div{
      width: 100%;
      height: 0.5rem;
    }
    .right-top{
      background: goldenrod;
    }
    .right-bottom{
      background: purple;
      position: absolute;//父元素开启定位后,相对于父元素的左上角移动
      left: 0.1rem;
      top:0.1rem;
    }
  }
  .box3{
    background: yellow;
  }
  .box4{
    background: plum;
  }
}


</style>

posted @ 2020-03-28 21:38  安静940  阅读(622)  评论(0编辑  收藏  举报