版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zhaihaohao1/article/details/84316119
position: fixed;元素的位置相对于浏览器窗口是固定位置。即使窗口是滚动的它也不会移动:
用法:
position: fixed;
left: 0px;
top: 0px;
下面主要讲相对定位和绝对定位
position: relative; 相对定位元素的定位是相对其正常位置。
position: absolute; 绝对定位的元素的位置相对于最近的已定位父元素,如果元素没有已定位的父元素,那么它的位置相对于:
结合下面的例子解释:
父元素box中, 必须设置 position: relative; 相对定位;
子元素icon1中, position: absolute; 绝对定位;
子元素icon1才会在父控件box里面摆放;
如果元素box不设置position: relative,则子元素是在body中摆放;
源码:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<style>
* {
margin: 0px;
padding: 0px;
}
.box {
width: 500px;
height: 500px;
background-color: yellow;
position: relative;
left: 20px;
top: 20px;
}
/*
* 父元素box中, 必须设置 position: relative; 相对定位
* 子元素icon1中, position: absolute; 绝对定位
* 子元素icon1才会在父控件box里面摆放
* 如果元素box不设置position: relative,则子元素是在body中摆放的
*/
.icon1 {
width: 200px;
height: 200px;
background-color: aqua;
position: absolute;
left: 20px;
top: 20px;
}
</style>
</head>
<body>
<div class="box">
<div class="icon1"></div>
</div>
</body>
</html>
参考链接:
http://www.runoob.com/css/css-positioning.html
根据上面知识,写了一个例子:
如图:
实现代码:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<style>
* {
margin: 0px;
padding: 0px;
}
.box {
width: 100%;
height: 100px;
background-color: yellow;
/*父元素设置为相对定位*/
position: relative;
left: 0px;
top: 0px;
}
/*
* 父元素box中, 必须设置 position: relative; 相对定位
* 子元素icon1中, position: absolute; 绝对定位
* 子元素icon1才会在父控件box里面摆放
* 如果元素box不设置position: relative,则子元素是在body中摆放的
*/
.icon1 {
/*子元素设置为绝对布局*/
position: absolute;
left: 0px;
top: 0px;
/*设置层级*/
z-index: 2;
line-height: 100px;
text-align: center;
width: 100px;
background-color: aqua;
font-size: 25px;
}
.biaoti{
position: absolute;
z-index: 1;
line-height: 100px;
text-align: center;
width: 100%;
background-color: crimson;
font-size: 30px;
}
.icon2{
position: absolute;
right: 0px;
top: 0px;
z-index: 2;
line-height: 100px;
text-align: center;
width: 100px;
background-color: greenyellow;
font-size: 25px;
}
</style>
</head>
<body>
<div class="box">
<div class="icon1">左边</div>
<div class="biaoti">标题</div>
<div class="icon2">右边</div>
</div>
</body>
</html>