static | relative | absolute | sticky | fixed
时间: 2023-11-10 17:07:37 浏览: 36
这里是CSS中五种常见的定位方式的介绍和用法:
1. static(静态定位):元素的位置遵循正常的文档流,不受top、bottom、left、right影响。
2. relative(相对定位):元素的位置相对于它在文档流中的初始位置进行定位,可以通过top、bottom、left、right属性进行微调。
3. absolute(绝对定位):元素的位置相对于最近的已定位祖先元素(position属性不为static)进行定位,如果没有已定位的祖先元素,则相对于文档的body元素进行定位。
4. fixed(固定定位):元素的位置相对于浏览器窗口进行定位,不随页面滚动而改变。
5. sticky(粘性定位):元素在跨越特定阈值前为相对定位,之后为固定定位。可以通过top、bottom、left、right属性进行微调。
下面是一个例子,展示了这五种定位方式的用法:
```html
<!DOCTYPE html>
<html>
<head>
<title>定位方式示例</title>
<style type="text/css">
.container {
height: 300px;
position: relative;
border: 1px solid black;
}
.box {
width: 100px;
height: 100px;
background-color: red; color: white;
text-align: center;
line-height: 100px;
font-size: 20px;
}
.static {
position: static;
}
.relative {
position: relative;
top: 50px;
left: 50px;
}
.absolute {
position: absolute;
top: 50px;
left: 50px;
}
.fixed {
position: fixed;
top: 50px;
left: 50px;
}
.sticky {
position: sticky;
top: 50px;
}
</style>
</head>
<body>
<div class="container">
<div class="box static">static</div>
<div class="box relative">relative</div>
<div class="box absolute">absolute</div>
<div class="box fixed">fixed</div>
<div class="box sticky">sticky</div>
</div>
</body>
</html>
```