CSS位置(一)---Position

Position:

absolute

生成绝对定位的元素,相对于 static 定位以外的第一个父元素进行定位。

relative

生成相对定位的元素,相对于其正常位置进行定位。

fixed

生成绝对定位的元素,相对于浏览器窗口进行定位。

static 默认值。没有定位。
inherit 规定应该从父元素继承 position 属性的值。

1.relative,相对定位:

(1)单模块从原点位置相对移动,从原来的位置移动对应的距离:如下,父元素从原来的位置向上和向右移动了100rpx的距离。

  <view class='father'>
  <view class='bro'>大儿子</view>
  <view class='son'>二儿子</view>
  </view>
.father{
  background-color: yellow;
  width: 300rpx;
  height: 300rpx;
  margin-top: 100rpx;
  margin-left: 100rpx;
  position: relative;
}

  

(2)两个模块从相对位置进行移动:

两个模块从自己的相对位置进行移动,都是从之前自己原来的位置出发。

.bro{
  background-color: red;
  width: 100rpx;
  height: 100rpx;
 position: relative;
  top: 100rpx;
  right: 100rpx;
}
.son{
  background-color: blue;
  width: 100rpx;
  height: 100rpx;
  position: relative;
  top: 20rpx;
  left: 20rpx; 
}

  

2.绝对定位:相对于 static 定位以外的第一个父元素进行定位。

(1)如果大儿子变为绝对定位,那么二儿子的位置也会发生改变,变为从原点出发。

可以看到,当大儿子变为绝对定位后,二儿子的位置从原来的地点变为了父元素的起点位置,大儿子采用绝对定位后,覆盖在二儿子上面,绝对定位存在着层级的关系。

.bro{
  background-color: red;
  width: 100rpx;
  height: 100rpx;
 position: absolute;
}
.son{
  background-color: blue;
  width: 100rpx;
  height: 100rpx;
 
}

  

如果给二儿子加上一个绝对/相对定位,二儿子就会达到最上层:

.bro{
  background-color: red;
  width: 100rpx;
  height: 100rpx;
  position: absolute;
}
.son{
  background-color: blue;
  width: 100rpx;
  height: 100rpx;
  position: absolute;
}

  

也可以通过相对定位将二儿子和大儿子一起放出来:

.bro{
  background-color: red;
  width: 100rpx;
  height: 100rpx;
  position: absolute;
}
.son{
  background-color: blue;
  width: 100rpx;
  height: 100rpx;
  position: relative;
  top: 100rpx;
  left: 100rpx;
}

  

3.固定定位:生成绝对定位的元素,相对于浏览器窗口进行定位。

.bro{
  background-color: red;
  width: 100rpx;
  height: 100rpx;
  position: fixed;
  top: 10rpx;
  left: 10rpx;
}
.son{
  background-color: blue;
  width: 100rpx;
  height: 100rpx;
  position: relative;
  top: 100rpx;
  left: 100rpx;
}

  

猜你喜欢

转载自www.cnblogs.com/moxuexiaotong/p/10070049.html