-
position定位
1.1 半自动居中 需要手动计算宽高
1.2 全自动居中 不需要知道宽高
-
position transform 不需要知道宽高
-
flex布局 align-items:center; justfly-content:center;
-
translateY布局 相对定位+translateY
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<!--
1. position定位
1.1 半自动居中 需要手动计算宽高
1.2 全自动居中 不需要知道宽高
2. position transform 不需要知道宽高
3. flex布局 align-items:center; justfly-content:center;
4. translateY布局 相对定位+translateY
-->
<style>
.wrap {
position: relative;
background-color: orange;
width: 300px;
height: 300px;
}
.example2 {
background-color: red;
width: 100px;
height: 100px;
position: absolute;
/* 1. position定位 */
/* 1.1 半自动居中 */
/* left: 50%;
top: 50%; */
/* margin: -50px 0 0 -50px; */
/* 1.2 全自动居中 */
/* top: 0;
right: 0;
left: 0;
bottom: 0;
margin: auto; */
/* 2. position transform */
/* left: 50%;
top: 50%; */
/* transform: translate(-50%,-50%) */
/* 4. transform:translateY(-50%); */
position: relative;
transform:translateY(-50%);
top: 50%;
margin: 0 auto;
}
</style>
</head>
<body>
<div class="wrap">
<div class="example2">
</div>
</div>
<script>
</script>
</body>
</html>
1. position定位
1.1 半自动居中 需要手动计算宽高
1.2 全自动居中 不需要知道宽高
2. position transform 不需要知道宽高
3. flex布局 align-items:center; justfly-content:center;
4. translateY布局 相对定位+translateY