1.定位加transform
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<style>
/* 定位加transform */
.father{
position: relative;
width: 200px;
height: 200px;
background-color: palevioletred;
}
.son{
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%,-50%);
width: 100px;
height: 100px;
background-color: yellow;
}
</style>
<body>
<div class="father">
<div class="son"></div>
</div>
<script>
</script>
</body>
</html>
2. 定位加margin,但子元素必须明确宽高
<style>
/* 定位加margin,但子元素必须明确宽高 */
.father{
position: relative;
width: 200px;
height: 200px;
background-color: palevioletred;
}
.son{
position: absolute;
left: 50%;
top: 50%;
/* 子元素宽度一半 */
margin-left: -50px;
/* 子元素高度一半 */
margin-top: -50px;
width: 100px;
height: 100px;
background-color: yellow;
}
</style>
3.使用flex
<style>
/* 使用flex */
.father{
display: flex;
justify-content: center;
align-items: center;
width: 200px;
height: 200px;
background-color: palevioletred;
}
.son{
width: 100px;
height: 100px;
background-color: yellow;
}
</style>
4.定位加margin:auto
<style>
/* 定位加margin:auto */
.father{
position: relative;
width: 200px;
height: 200px;
background-color: palevioletred;
}
.son{
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
margin: auto;
width: 100px;
height: 100px;
background-color: yellow;
}
</style>