介绍
属性指定了元素的定位类型
基本属性
- static : 默认值。没有定位,元素出现在正常的流中
- relative : 相对定位
- fixed : 固定定位
- absolute : 绝对定位
- sticky : 粘性定位
用法
static
正常的布局行为,即元素在文档常规流中当前的布局位置。此时top, right, bottom, left
和 z-index
属性无效。
例:
.box {
display: inline-block;
height: 100px;
width: 100px;
line-height: 100px;
text-align: center;
background-color: #F19EC4;
border-radius: 8px;
color: #FFFFFF;
}
.position-static {
position: static;
background-color: #7FD0F3;
}
<div class="box">1</div>
<div class="box position-static">2</div>
<div class="box">3</div>
效果:
![](https://img.haomeiwen.com/i1638147/fc2b1bd1c3b7b12f.png)
relative
相对定位
元素先放置在未添加定位时的位置,再在不改变页面布局的前提下调整元素位置。
position:relative
对 table-*-group, table-row, table-column, table-cell, table-caption
元素无效
例:
.position-relative {
position: relative;
background-color: #7FD0F3;
top: 20px;
left: 20px;
}
<div class="box">1</div>
<div class="box position-relative">2</div>
<div class="box">3</div>
效果:box2在原来的位置上发生了偏移
![](https://img.haomeiwen.com/i1638147/79649c51fae9ea0c.png)
fixed
固定定位
不为元素预留空间,而是通过指定元素相对于屏幕视口(viewport)的位置来指定元素位置。元素的位置在屏幕滚动时不会改变。
例:
.position-fixed {
position: fixed;
background-color: #7FD0F3;
bottom: 10px;
left: 10px;
}
<div class="box">1</div>
<div class="box position-fixed">2</div>
<div class="box">3</div>
效果:图中box2被定位在底部靠左的位置
![](https://img.haomeiwen.com/i1638147/c79708ae7963ad31.gif)
absolute
绝对定位
不为元素预留空间,通过指定元素相对于最近的非 static 定位祖先元素的偏移,来确定元素位置。绝对定位的元素可以设置外边距(margins),且不会与其他边距合并。
例:
.position-absolute {
position: absolute;
background-color: #7FD0F3;
bottom: 10px;
left: 10px;
}
<div class="box">1</div>
<div class="box position-absolute">2</div>
<div class="box">3</div>
效果:与fixed相似,但会随着屏幕滚动
![](https://img.haomeiwen.com/i1638147/54c96682b6f9fd19.gif)
sticky
粘性定位
元素先按照普通文档流定位,然后相对于该元素在流中的 flow root(BFC)和 containing block(最近的块级祖先元素)定位。光描述可能会一脸懵逼,看效果好了
须指定 top, right, bottom
或 left
四个阈值其中之一,才可使粘性定位生效。否则其行为与相对定位相同。
(兼容性不大好)
例:多个元素使用sticky
.position-sticky {
position: sticky;
position: -webkit-sticky;
background-color: #7FD0F3;
top: 10px;
}
<div class="box">1</div>
<div class="box position-sticky">2</div>
<div class="box">3</div>
<div class="box">4</div>
<div class="box position-sticky">5</div>
<div class="box">6</div>
<div class="box">7</div>
<div class="box position-sticky">8</div>
<div class="box">9</div>
<div class="box">9</div>
效果:
![](https://img.haomeiwen.com/i1638147/eb8bbbdd6d12d0ff.gif)
but!在caniuse上查了下,兼容性兼容确实不好,就当学习了吧
![](https://img.haomeiwen.com/i1638147/fbccd4c458c872ce.png)
图片来自:https://caniuse.com/#tables
参考
https://developer.mozilla.org/zh-CN/docs/Web/CSS/position
http://zh.learnlayout.com/position.html
相关阅读
CSS : 入门
CSS : display
CSS : float
CSS : 对齐、居中
有错误之处,感谢指出,接收批评
网友评论