今天是2018年7月16日
1.相對(duì)定位
給元素設(shè)置
position: relative;可以使元素處于相對(duì)定位中。
<style>
/* 相對(duì)定位就是元素在頁(yè)面上正常的位置 */
div{
width: 100px;
height: 100px;
background-color: red;
position: relative;
top: 0px;
left:0px;
/* 相對(duì)定位一般不適用right/bottom */
right: 0px;
bottom: 0px;
}
</style>
2.絕對(duì)定位
不同于相對(duì)定位,絕對(duì)定位是指在父元素中絕對(duì)的位置
<style>
.parent{
width: 200px;
height: 200px;
background-color: red;
position: relative;
}
.child{
width: 50px;
height: 50px;
background-color: blue;
position: absolute;
right: 0;
}
</style>
3.元素的垂直水平居中
利用絕對(duì)定位和相對(duì)定位,可以實(shí)現(xiàn)元素在父類中的水平垂直居中
原理是使父元素相對(duì)定位,子元素絕對(duì)定位,給子元素50%定位后利用margin-top和margin-left回移子元素width和height屬性的一半。
<style>
*{padding: 0;margin: 0}
.parent{
width:300px;
height: 300px;
background-color: red;
position: relative;
}
.child{
width: 50px;
height: 50px;
position: absolute;
left: 50%;
top: 50%;
background-color: blue;
margin-top: -25px;
margin-left: -25%;
}
</style>
4.固定定位
固定定位可以使元素不受到滾動(dòng)條的影響,始終固定在某一個(gè)位置
<style>
body{
line-height: 30px;
}
div{
width: 20px;
height: 50px;
background: tomato;
position: fixed;
right: 10px;
bottom: 500px;
}
</style>
5.Z-index
給元素設(shè)置z-index值可以更改元素覆蓋情況下的優(yōu)先顯示順序
<style>
.parent{
width: 300px;
height: 300px;
background-color: red;
position: relative;
}
.one{
width: 100px;
height: 200px;
background-color: green;
position: absolute;
z-index: 2;
}
.two{
width: 200px;
height: 100px;
background-color: blue;
position: absolute;
z-index: 3;
}
.parent:hover .one{
z-index:20;
}
</style>