四种实现父盒子里子盒水平垂直居中的技巧
最编程
2024-02-13 08:17:51
...
方法一:
子盒子先定位top50%left50%,然后通过margin让其向上,向左移动自身宽高的一半
<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>
.father {
position: relative;
width: 500px;
height: 500px;
background-color: red;
margin: auto;
}
.son {
position: absolute;
top: 50%;
left: 50%;
margin-top: -50px;
margin-left: -100px;
width: 200px;
height: 100px;
background-color: green;
}
</style>
</head>
<body>
<div class="father">
<div class="son"></div>
</div>
</body>
</html>
效果图:
方法二:
方法二属于方法一的进阶版,子盒子先定位top50%left50%,然后通过位移让其向上,向左移动自身宽高的一半
<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>
.father {
position: relative;
width: 500px;
height: 500px;
background-color: red;
margin: auto;
}
.son {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 200px;
height: 100px;
background-color: green;
margin: auto;
}
</style>
</head>
<body>
<div class="father">
<div class="son"></div>
</div>
</body>
</html>
效果图:
方法三:
子盒子设置四个方向定位为0,然后通过margin:auto 让其居中
<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>
.father {
position: relative;
width: 500px;
height: 500px;
background-color: red;
margin: auto;
}
.son {
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
width: 200px;
height: 100px;
background-color: green;
margin: auto;
}
</style>
</head>
<body>
<div class="father">
<div class="son"></div>
</div>
</body>
</html>
效果图:
方法四:
flex布局
<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>
.father {
display: flex;
justify-content: center;
align-items: center;
width: 500px;
height: 500px;
background-color: red;
margin: auto;
}
.son {
width: 200px;
height: 100px;
background-color: green;
}
</style>
</head>
<body>
<div class="father">
<div class="son"></div>
</div>
</body>
</html>
效果图: