<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>相对定位</title>
<style>
.father{
height: 500px;
background-color: bisque;
}
.son1{
height: 100px;
background-color: #00ff7f;
}
.son2{
height: 100px;
background-color: #fff701;
}
.son3{
height: 100px;
background-color: #0026ff;
}
.son4{
height: 100px;
background-color: #08ffeb;
}
</style>
</head>
<body>
<div class="father">
<div class="son1">son1</div>
<div class="son2">son2</div>
<div class="son3">son3</div>
<div class="son4">son4</div>
</div>
</body>
</html>
子绝父相:给父元素添上相对定位,子元素添上绝对定位
<style>
.father{
height: 500px;
background-color: bisque;
/* 父元素相对定位 */
position: relative;
}
.son1{
height: 100px;
background-color: #00ff7f;
/* 绝对定位 */
/* position: absolute; */
}
.son2{
height: 100px;
background-color: #fff701;
/* 绝对定位 */
/* position: absolute; */
}
.son3{
height: 100px;
background-color: #0026ff;
/* 绝对定位 */
position: absolute;
}
.son4{
height: 100px;
background-color: #08ffeb;
}
</style>
只有son3是绝对定位的时候
son2和son3都是绝对定位的时候
.son2{
height: 100px;
background-color: #fff701;
/* 绝对定位 */
position: absolute;
}
![
son1,son2和son3都是绝对定位的时候
.son1{
height: 100px;
background-color: #00ff7f;
/* 绝对定位 */
position: absolute;
}
son1,son2,son3和son4都是绝对定位的时候
.son4{
height: 100px;
background-color: #08ffeb;
/* 绝对定位 */
position: absolute;
}
可以看到,元素在没有定义宽度(或高度)的情况下,宽度由元素里面的内容决定
<style>
.father{
height: 500px;
background-color: bisque;
/* 父元素相对定位 */
position: relative;
}
.son1{
height: 100px;
background-color: #00ff7f;
/* 绝对定位 */
position: absolute;
z-index: 1000;
}
.son2{
width: 40px;
height: 100px;
background-color: #fff701;
/* 绝对定位 */
position: absolute;
z-index: 100;
}
.son3{
width: 50px;
height: 100px;
background-color: #0026ff;
/* 绝对定位 */
position: absolute;
z-index: 10;
}
.son4{
width: 70px;
height: 100px;
background-color: #08ffeb;
/* 绝对定位 */
position: absolute;
z-index: 0;
}
</style>
给元素块添加宽度,并调节上下顺序
.son1{
/* height: 100px; */
background-color: #00ff7f;
/* 绝对定位 */
position: absolute;
z-index: 1000;
}
.son2{
width: 40px;
height: 100px;
background-color: #fff701;
/* 绝对定位 */
position: absolute;
z-index: 100;
left: 50px;
top: 50px;
}
.son3{
width: 50px;
height: 100px;
background-color: #0026ff;
/* 绝对定位 */
position: absolute;
z-index: 10;
left: 100px;
top: 100px;
}
.son4{
width: 70px;
height: 100px;
background-color: #08ffeb;
/* 绝对定位 */
position: absolute;
z-index: 0;
left: 200px;
top: 200px;
}
.son2{
width: 40px;
height: 100px;
background-color: #fff701;
/* 绝对定位 */
position: absolute;
z-index: 100;
left: 100px;
top: 100px;
}