position 常见布局属性

303 阅读2分钟

前言

positon属性,在平时布局中经常使用,无论是 小程序、react-native、react-app、vue、h5,只要涉及到html相关布局,基本上都会用到

这里提一下, position 属性设置的都是关于自身的布局改变,而前面看到的 flex 相关属性,这个是设置其子视图布局的

position

absolute

生成绝对定位的元素,相对于 第一个static 定位以外的祖先节点进行定位,那个祖先节点就是他的包含块。

元素的位置通过 lefttoprightbottom 属性进行规定。

fixed

生成绝对定位的元素,相对于窗口或者第一个变形祖先进行定位。

元素的位置通过 lefttoprightbottom 属性进行规定。

relative

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

因此,"left:20" 会向元素的 left 位置添加 20 像素空间,即向右移动20像素。

static

默认值,没有定位,元素出现在正常的流中(忽略 top, bottom, left, right 或者 z-index 声明)。

inherit

规定应该从父元素继承 position 属性的值(父元素是 absolute,那么它也是)。

看如下代码:

xml、wxml

<view class="container">
  <view class='view1'>1</view>
  <view class='view2'>2</view>
  <view class='view3'>3</view>
  <view class='view4'>4</view>
</view>

css、wxss

.container {
  display: flex;
  flex-direction: column;
  align-items: center;
  background: bisque;
}

.view1 {
  width: 128rpx;
  height: 128rpx;
  background-color: red;
}
.view2 {
  width: 128rpx;
  height: 128rpx;
  background-color: rebeccapurple;
}
.view3 {
  width: 128rpx;
  height: 128rpx;
  background-color: royalblue;
}
.view4 {
  width: 128rpx;
  height: 128rpx;
  background-color: paleturquoise;
}

image.png

absolute

现在我们对 view2 添加下面这个类

.other { position: relative; top: 30rpx; left: 50rpx; } wxml中修改:

<view class="container"> <view class='view1'>1</view> <view class='view2 other'>2</view> <view class='view3'>3</view> <view class='view4'>4</view> </view> image.png

可见relative这个属性相对于原来的位置进行偏移。

absolute

position 更改为 absolute

.other {
  position: absolute;
  top: 30rpx;
  left: 50rpx;
}

image.png

发现absolute并没有保留原来的位置,并且坐标偏移是以最近的跟视图为准进行偏移

注意:当碰到 父视图的 position 不是 static 的时候,其相对于父布局偏移

fixed

这个就不额外测试了,其 相对于窗口 进行绝对布局,可以认为其父布局是窗口,进行绝对布局,即:相对于窗口四边进行偏移

sticky

粘性定位,一般用于吸顶效果,常见页面标题置顶,上划时避免隐藏,其位置相对于第一个滚动祖先元素

.sticky {
    position: 'sticky',
    top: 0, //相对与顶部距离会吸到那个位置
    background-color: green;
}