2022年7月18日黑子若白到此一游。
1.定位子绝父相,缺点需要知道子盒子的宽高。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
.dad {
position: relative;
width: 200px;
height: 200px;
border: 1px solid red;
}
.son {
/* 需要知道子元素的宽高 */
/* top、left为50%, 外边距左上为它的负一半*/
position: absolute;
width: 50px;
height: 50px;
left: 50%;
top: 50%;
margin-left: -25px;
margin-top: -25px;
background-color: yellow;
}
</style>
</head>
<body>
<div class="dad">
<div class="son"></div>
</div>
</body>
</html>
定位+transform
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
.dad {
position: relative;
width: 200px;
height: 200px;
border: 1px solid red;
}
.son {
/* 定位+transform 问题:兼容性不好 */
position: absolute;
width: 50px;
height: 50px;
left: 50%;
top: 50%;
transform:translate(-50%,-50%);
background-color: skyblue;
}
</style>
</head>
<body>
<div class="dad">
<div class="son"></div>
</div>
</body>
</html>
flex弹性布局兼容性不好
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
.dad {
display: flex;
justify-content: center;
align-items: center;
width: 200px;
height: 200px;
border: 1px solid red;
}
.son {
/*flex:兼容性不好 */
width: 50px;
height: 50px;
background-color: red;
}
</style>
</head>
<body>
<div class="dad">
<div class="son"></div>
</div>
</body>
</html>