自学前端系列之HTML与CSS
第十一节:CSS之position定位
1.static(静态定位)
是 position 属性的默认值,表示块保留在原本位置,不会被top bottom left right和z-index重新定位。
<!DOCTYPE html>
<html>
<head>
<style>
div {
height: 50px;
width: 20px;
position: static;
top: 100px;
left: 100px;
background-color: aquamarine;
}
</style>
</head>
<body>
<div></div>
</body>
</html>
由于位置是static,所以它并不在top:100px;left:100px的地方,而在top:0px;left:0px的地方
2.fixed(固定定位)
相对于浏览器的创建进行定位,可使用 top、right、bottom、left 这 4 个属性来定义元素相对于浏览器窗口的位置。由于元素被固定不会随着滚动条的拖动而改变位置,所以出现在每页的固定位置。
<!DOCTYPE html>
<html>
<head>
<style>
.body {
overflow: scroll;
width: 10px;
}
div {
height: 70px;
width: 50px;
position: fixed;
top: 100px;
left: 100px;
background-color: rgb(32, 142, 233);
}
</style>
</head>
<body class="body">
<div></div>
</body>
</html>
3.relative(相对定位)
相对定位将元素从原来的位置通过 top、bottom、left 和 right 四个属性向上、向下、向左或者向右移动来定位。它的元素可以移动并与其他元素重叠,但会保留元素默认位置处的空间。
<!DOCTYPE html>
<html>
<head>
<style>
div {
border: 1px solid black;
}
div.decorate {
width: 150px;
height: 100px;
background-color: #2da107;
position: relative;
top: 50px;
left: 30px;
}
p {
width: 100px;
height: 100px;
background-color: rgb(109, 56, 56);
}
</style>
</head>
<body>
<div>
<div class="decorate"></div>
<p></p>
</div>
</body>
</html>
4.absolute(绝对定位)
绝对定位,是相对于最近的且不是static定位的父元素来定位。如果找不到符合条件的父级元素则会相对与浏览器窗口来进行定位。可以使用 top、bottom、left 和 right 四个属性来设置元素相对于父元素或浏览器窗口不同方向上的移动量
<!DOCTYPE html>
<html>
<head>
<style>
div {
border: 1px solid black;
}
div.decorate {
width: 150px;
height: 100px;
background-color: #2da107;
position: absolute;
top: 50px;
left: 30px;
}
p {
width: 100px;
height: 100px;
background-color: rgb(109, 56, 56);
}
</style>
</head>
<body>
<div>
<div class="decorate"></div>
<p></p>
</div>
</body>
</html>