Skip to content

position 定位

position 属性用于指定一个元素在文档中的定位方式。top,right,bottom 和 left 属性则决定了该元素的最终位置。

sticky 粘性定位

sticky 元素会“固定”在离它最近的一个拥有“滚动机制”的祖先上(当该祖先的 overflow 是 hidden、scroll、auto 或 overlay 时),即便这个祖先不是最近的真实可滚动祖先。

相对祖先定位

但区域受限于父容器大小,一旦父容器不可见,定位元素也随之消失。

粘性布局--外部
vue
<template>
  <div class="box">
    <div class="sticky" style="z-index: 21">粘性布局--外部</div>
  </div>
</template>

<style lang="scss" scoped>
.box {
  height: 50vh;
}
.sticky {
  position: sticky;
  top: 0;
  background-color: #aaa;
}
</style>

限定当前滚动

内容
内容
内容
内容
内容
内容
内容
内容
内容
内容
粘性布局
vue
<template>
  <div class="scroll">
    <div v-for="item of 10">内容</div>
    <div class="sticky">粘性布局</div>
    <div class="box"></div>
  </div>
</template>

<style lang="scss" scoped>
.scroll {
  overflow: auto;
  height: 200px;
  border: 1px solid #000;
}
.box {
  height: 200vh;
}
.sticky {
  position: sticky;
  top: 0;
  background-color: #aaa;
}
</style>

多级定位

sticky 元素粘在父容器上,当父容器不可见时,该元素也随消失。

粘性布局1
内容
内容
内容
内容
内容
内容
粘性布局2
内容
内容
内容
内容
内容
内容
粘性布局3
内容
内容
内容
内容
内容
内容
粘性布局4
内容
内容
内容
内容
内容
内容
粘性布局5
内容
内容
内容
内容
内容
内容
粘性布局6
内容
内容
内容
内容
内容
内容
粘性布局7
内容
内容
内容
内容
内容
内容
粘性布局8
内容
内容
内容
内容
内容
内容
粘性布局9
内容
内容
内容
内容
内容
内容
粘性布局10
内容
内容
内容
内容
内容
内容
vue
<template>
  <div class="scroll">
    <div v-for="item of 10">
      <div class="sticky">粘性布局{{ item }}</div>
      <div v-for="item of 6">内容</div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.scroll {
  overflow: auto;
  height: 200px;
  border: 1px solid #000;
}
.box {
  height: 200vh;
}
.sticky {
  position: sticky;
  top: 0;
  background-color: #aaa;
}
</style>

设置 bottom 可粘在底部

粘性布局--底部
vue
<template>
  <div class="sticky" style="bottom: 0">粘性布局--底部</div>
</template>

<style lang="scss" scoped>
.scroll {
  overflow: auto;
  height: 200px;
  border: 1px solid #000;
}
.box {
  height: 200vh;
}
.sticky {
  position: sticky;
  top: 0;
  background-color: #aaa;
}
</style>