小程序position属性探析

在学习小程序时,有时候页面布局总出问题。因此对position属性进行一些探析。

position属性可以设置为static,relative,absolute,fixed,inherit,-ms-page,initial,unset 这些值。本文主要讨论最常用的三个:

  • relative 相对于自身位置的偏移,自身原来位置依然保留
  • absolute 相对于父元素的偏移,自身原来位置不保留
  • fixed 和absolute类似,但是父元素为视窗本身

文字看上去不好理解,所以我们动手试试。

1
2
3
4
5
<view class="container">
<view class="cube red">a</view>
<view class="cube gray">b</view>
<view class="cube gold">c</view>
</view>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
.container{
display: flex;
flex-direction: column;
}
.cube{
width: 100rpx;
height: 100rpx;
}
.red{
background-color: red;
}
.gray{
background-color: gray;
}
.gold{
background-color: gold;
}

根据代码,我们应该看到三个方块整齐的竖着排着:
1

relative

首先我们来看看relative:

1
2
3
4
5
<view class="container">
<view class="cube red">a</view>
<view class="cube gray other">b</view>
<view class="cube gold">c</view>
</view>

1
2
3
4
5
.other{
position: relative;
top:50rpx;
left: 50rpx;
}

按照描述,我们应该看到A和C还在原来的位置,B向右下角平移了:
2
结果验证了我们的理解。

absolute

接下来我们来看看absolute:

1
2
3
4
5
.other{
position: absolute;
top:50rpx;
left: 50rpx;
}

按照描述,我们应该看到A还在原来的位置,C在B原来的位置,而B应该跑到了整个页面的左上角:
3
结果验证了我们的理解。

fixed

接下来我们来看看absolute:

1
2
3
4
5
.other{
position: fixed;
top:50rpx;
left: 50rpx;
}

按照描述,我们应该看到和absolute一样
4
结果验证了我们的理解。
那fixed和absolute的区别是什么呢?
我们来把container修改一下:

1
2
3
4
5
6
.container{
display: flex;
flex-direction: column;
position:relative;
top:200rpx;
}

我们将container相对于整个页面,向下挪了200rpx,按照描述,absolute下B相对于container平移了50,所以相对于整个页面平移了200+50。而fixed是相对于页面,因此和前面一样。两个结果如下所示,第一张为absolute,第二张为fixed。可以看出效果和预期一致。
absolute
fixed