CSS中给我们提供的另一种定位方法——position。
又可以分为自动定位(static),相对定位(relative),绝对定位(absolute),和固定定位(fixed)。
自动定位:元素使用正常的布局行为,即元素在文档常规流中当前的布局位置。此时 top, right, bottom, left 和 z-index 属性无效。
相对定位:相对原本的位置进行偏移,在不改变页面布局的情况下。会占据原有的空间。
绝对定位:元素会被移出正常文档流,并不为元素预留空间,通过指定元素相对于最近的非 static 定位祖先元素的偏移,来确定元素位置。绝对定位的元素可以设置外边距(margins),且不会与其他边距合并。
举个例子:
<div class="box one">One</div>
<div class="box two">Two</div>
<div class="box three">Three</div>
<div class="box four">Four</div>
.box {
display: inline-block;
background: red;
width: 100px;
height: 100px;
float: left;
margin: 20px;
color: white;
}
.three {
position: absolute;
top: 20px;
left: 20px;
}
固定定位:元素会被移出正常文档流,并不为元素预留空间,而是通过指定元素相对于屏幕视口(viewport)的位置来指定元素位置。元素的位置在屏幕滚动时不会改变。
举例:
<div class="box">hello world</div>
<style>
body{
height: 1000px;
}
.box{
width: 100px;
height: 100px;
background-color: red;
position: fixed;
left: 100px;
top: 100px;
}
</style>
小技巧,通过固定定位来设置自动居中。
<style>
body{
height: 1000px;
}
.box{
width: 100px;
height: 100px;
background-color: red;
margin: auto;
position: fixed;
left: 0px;
right: 0px;
top: 0px;
bottom: 0px;
}
</style>