初识CSS定位
position 属性指定了元素的定位类型。
position 属性的五个值:
static
relative
fixed
absolute
sticky
元素可以使用的顶部,底部,左侧和右侧属性定位。然而,这些属性无法工作,除非是先设定position属性。他们也有不同的工作方式,这取决于定位方法。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
.div1{
width: 200px;
height: 200px;
background-color: pink;
}
.div2{
width: 200px;
height: 200px;
background-color: red;
}
</style>
</head>
<body>
<div class="div1"></div>
<div class="div2"></div>
</body>
</html>
这里作为原位置,未加定位,接下来会与此代码比较
- static
静态定位是所有元素的默认定位方式,当position属性的取值为static时,可以将元素定位于静态位置。 所谓静态位置就是各个元素在HTML文档流中默认的位置。
静态定位的元素不会受到 top, bottom, left, right影响 - relative
相对定位元素的定位是相对其正常位置。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
.div1{
width: 200px;
height: 200px;
background-color: pink;
position: relative;
top: 500px;
}
.div2{
width: 200px;
height: 200px;
background-color: red;
}
</style>
</head>
<body>
<div class="div1"></div>
<div class="div2"></div>
</body>
</html>
我们可以观察到,相对定位会保留在文档流中的位置。
- fixed
它以浏览器窗口作为参照物来定义网页元素。当position属性的取值为fixed时,即可将元素的定位模式设置为固定定位。
固定定位是一种特殊的绝对定位 - absolute
绝对定位的元素的位置相对于最近的已定位父元素,如果元素没有已定位的父元素,那么它的位置相对于html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
.div1{
width: 200px;
height: 200px;
background-color: pink;
position: absolute;
top: 500px;
}
.div2{
width: 200px;
height: 200px;
background-color: red;
}
</style>
</head>
<body>
<div class="div1"></div>
<div class="div2"></div>
</body>
</html>
可以看到,绝对定位在不会保留在文档流中的位置。