大家好,今天给大家分享一下CSS绝对定位和固定定位
定位:基于xxxx定位,上下左右的位置变化
1.没有父级元素定位的情况下,相对于浏览器定位
2.假设父级元素存在定位,我们通常会相对于父级元素进行偏移
3.在父级元素范围内移动
相对于父级或浏览器的位置,进行指定的偏移,绝对定位的话,它不存在标准文档流中,原来的位置不会被保留
先讲绝对定位:
写源码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
div{
margin: 10px;
padding: 5px;
font-size: 12px;
line-height: 25px;
}
#father{
border: 1px solid brown;
padding: 0;
}
#first{
border: green 1px dashed;
background-color: brown;
}
#second {
border: lightsalmon 1px dashed;
background-color: yellow;
}
#third{
border: green 1px dashed;
background-color: darkorchid;
}
}
</style>
</head>
<body>
<div id="father">
<div id="first">第一个盒子</div>
<div id="second">第二个盒子</div>
<div id="third">第三盒子</div>
</div>
</body>
</html>
看效果:
绝对定位:
#second {
border: lightsalmon 1px dashed;
background-color: yellow;
position: absolute;
/* 这就是绝对定位*/
看结果:
写代码:
#second {
border: lightsalmon 1px dashed;
background-color: yellow;
position: absolute;
/* 这就是绝对定位*/
right: 30px;
看效果:
这是相对于浏览器定位
父级元素给个定位
#father{
border: 1px solid brown;
padding: 0;
position: relative;
}
#second {
border: lightsalmon 1px dashed;
background-color: yellow;
position: absolute;
/* 这就是绝对定位*/
right: 30px;
top:-10px;
/* 相对于父级元素*/
显示效果:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
body{
height: 100px;
}
div:nth-of-type(1) {
/*绝对定位 相对于浏览器*/
width: 100px;
height: 100px;
background: lightsalmon;
position: absolute;
/*绝对定位 相对于浏览器*/
right: 0;
bottom: 0;
}
div:nth-of-type(2){
/*固定定位*/
width: 50px;
height: 50px;
background: yellow;
position: fixed;
/*固定定位*/
}
</style>
</head>
<body>
<div>div1</div>
<div>div2</div>
</body>
</html>
看效果:
好了,有关于CSS绝对定位和固定定位就到这里了,谢谢大家。