一、absolute定位
absolute定位是相对于最近的带有position定位的祖先元素进行定位的,如果没有带有position定位的祖先元素,则是相对于body元素进行定位。
例如,我们要将一个元素放置在页面的右上角:
<html>
<style>
.box {
width: 200px;
height: 200px;
background-color: yellow;
position: absolute; // 添加定位属性
top: 0; // 距离页面顶部0px
right: 0; // 距离页面右侧0px
}
</style>
<body>
<div class="box"></div>
</body>
</html>
这样就可以将元素放置在右上角。
二、relative定位
relative定位是相对于元素本身原来的位置进行定位的,原来占据的位置会被保留。
例如,我们想要将一个元素向下移动20px:
<html>
<style>
.box1 {
width: 200px;
height: 200px;
background-color: yellow;
}
.box2 {
width: 100px;
height: 100px;
background-color: red;
position: relative; // 添加定位属性
top: 20px; //向下移动20px
}
</style>
<body>
<div class="box1">
<div class="box2"></div>
</div>
</body>
</html>
根据上述代码,我们创建了两个不同的div元素,.box2添加了relative定位并移动了20px,但是原来的位置不会变化,.box1元素在页面上保留了原始的位置.
三、fixed定位
fixed定位是相对于浏览器窗口进行定位的,当滚动页面时,元素也不会移动。
例如,我们需要将一个元素始终固定在页面右下角:
<html>
<style>
.box {
width: 200px;
height: 200px;
background-color: yellow;
position: fixed; //添加定位属性
bottom: 0; //距离页面底部0px
right: 0; //距离页面右侧0px
}
</style>
<body>
<div class="box"></div>
</body>
</html>
现在,无论您如何滚动页面,元素始终保留在右下角。
四、sticky定位
Sticky定位类似relative和fixed的混合体,当滚动到某个阈值时它变为fixed定位,这可以实现“黏性”效果。
例如,我们想要在页面顶部添加一个黏性导航条:
<html>
<style>
nav {
position: sticky; //添加定位属性
top: 0;
width: 100%;
background-color: blue;
color: white;
padding: 20px;
}
section {
height: 500px;
}
</style>
<body>
<nav>
<ul>
<li><a href="#">Home</a></li>
<li><a href="#">Blog</a></li>
<li><a href="#">Contact</a></li>
</ul>
</nav>
<section></section>
</body>
</html>
现在,当您滚动页面时,导航条将“黏”在顶部,直到您到达页面底部。
五、z-index属性
z-index属性规定了一个元素的堆叠顺序,也就是说,哪一个元素位于另一个元素的前面或后面。
例如,我们创建两个元素,一个具有更大的z-index值:
<html>
<style>
.box1 {
width: 200px;
height: 200px;
background-color: yellow;
position: absolute;
top: 50px;
left: 50px;
z-index: 1; //添加z-index属性
}
.box2 {
width: 200px;
height: 200px;
background-color: red;
position: absolute;
top: 100px;
left: 100px;
z-index: 2; //添加z-index属性
}
</style>
<body>
<div class="box1"></div>
<div class="box2"></div>
</body>
</html>
在这个例子中,.box1元素具有更低的z-index值,.box2元素具有更高的z-index值,将其放在.box1元素的顶部。注意:更高的z-index值表示元素更接近屏幕的前景。
六、绝对定位与响应式布局的结合使用
使用响应式布局时,需要使用不同的CSS规则来解决页面在不同设备上的显示问题。在这种情况下,绝对定位非常有用。
例如,我们需要在大屏幕上和小屏幕上有不同的header布局:
<html>
<style>
@media screen and (min-width: 768px) { //媒体查询:屏幕大于等于768px
header {
width: 100%;
height: 100px;
background-color: blue;
position: absolute;
top: 0;
left: 0;
z-index: 1;
}
main {
position: relative;
top: 100px;
}
}
@media screen and (max-width: 767px) { //媒体查询:屏幕小于768px
header {
width: 100%;
height: 50px;
background-color: red;
position: absolute;
top: 0;
left: 0;
z-index: 1;
}
main {
position: relative;
top: 50px;
}
}
</style>
<body>
<header></header>
<main></maim>
</body>
</html>
在这个例子中,通过@media查询来检测屏幕大小,如果屏幕大小大于等于768px,则.header元素是高100px,宽100%并且位于页面顶部。在下面的元素中,主要内容在.header元素下面。如果屏幕大小小于768px,则.header元素具有较小的高度(50px),并且位置相同。.main元素有一个相对位置偏移,以使其避免与.header元素重叠。
原创文章,作者:小蓝,如若转载,请注明出处:https://www.506064.com/n/195610.html
微信扫一扫
支付宝扫一扫