CSS进阶-定位(二)
8、定位
- 定位元素的层级比普通元素高,定位元素之间的层级相等,若发生覆盖,则后写的元素覆盖在先写的元素上面。
属性名 | 描述 |
---|---|
position:relative; | 相对定位(相对默认位置进行定位,不脱离文档流,仍占据页面位置) |
position:absolute; | 绝对定位(脱离文档流,相对包含块进行定位) |
position:fixed; | 相对浏览器的视口进行固定定位 |
8.1 相对定位
- 可以和浮动、margin同时使用;
- 不能将元素转换为定位元素。
<style>
.outbox {
width: 600px;
height: 600px;
background-color: #888;
}
.box {
width: 100px;
height: 100px;
}
.box1 {
background-color: antiquewhite;
}
.box2 {
background-color: aqua;
position: relative;
left: 10px;
top: 10px;
}
.box3 {
background-color: aquamarine;
}
</style>
8.2 绝对定位
包含块:
1、对于没有脱离文档流的元素:包含块就是父元素;
2、对于脱离文档流的元素:包含块就是第一个有定位属性的祖先元素
绝对定位与浮动同时设置时,浮动失效;
将设置的元素转换为定位元素。
<style>
.box {
width: 200px;
height: 200px;
position: relative;
background-color: red;
}
.box1 {
width: 200px;
height: 200px;
background-color: black;
}
.box:hover .box2{
left: 200px;
}
.box2 {
width: 200px;
height: 200px;
background-color: green;
position: absolute;
left: 0px;
top: 0px;
}
.box3 {
width: 70px;
height: 70px;
background-color: #888;
text-align: center;
line-height: 70px;
position: absolute;
top: 350px;
left: 250px;
cursor: pointer;
}
</style>
8.3 固定定位
- 脱离文档流,对后面的兄弟元素、父元素有影响;
- 浮动和固定定位同时设置,浮动失效;
- 将元素转换为定位元素。
<style>
.outer{
background-color: antiquewhite;
width: 500px;
height: 750px;
padding: 20px;
}
.d1,
.d2,
.d3{
width: 300px;
height: 300px;
}
.d1 {
background-color: aqua;
}
.d2{
background-color: aquamarine;
position: fixed;
right: 0;
bottom: 0;
}
.d3 {
background-color:blueviolet;
}
</style>
8.4 粘性定位
- 不脱离文档流;
- 能和浮动、margin同时使用;
- 将元素转换为定位元素。
<style>
* {
margin: 0;
padding: 0;
}
body {
height: 2000px;
}
.header {
height: 100px;
text-align: center;
line-height: 100px;
background-color: aquamarine;
}
.items {
background-color: rgb(144, 172, 196);
font-size: 30px;
line-height: 30px;
}
.A,
.B,
.C {
height: 100px;
background-color: aqua;
position: sticky;
line-height: 100px;
top: 0;
}
</style>
8.5 定位的层级
使用z-index设置定位元素的优先级,z-index越大,元素的层级越高。
<style>
.outer {
height: 600px;
width: 600px;
background-color: aliceblue;
padding: 10px;
position: relative;
}
.d1 {
width: 200px;
height: 200px;
background-color: aqua;
}
.d2 {
width: 200px;
height: 200px;
background-color: aquamarine;
position: relative;
top: -150px;
left: 50px;
}
.d3 {
width: 200px;
height: 200px;
background-color: blanchedalmond;
position: absolute;
top: 110px;
left: 110px;
}
.d4 {
width: 200px;
height: 200px;
background-color: blueviolet;
position: fixed;
top: 160px;
left: 160px;
}
</style>
8.6 定位元素的特殊应用
<style>
.d1 {
width: 400px;
height: 400px;
background-color: antiquewhite;
position: relative;
}
.d2 {
width: 200px;
height: 200px;
background-color: aqua;
position: absolute;
/* 第一种方式 */
/* top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto; */
/* 第二种方式 */
left: 50%;
top: 50%;
margin-top: -100px;
margin-left: -100px;
}
</style>