关于盒子水平垂直居中的方法
方法一:利用定位实现水平垂直居中
<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>
</head>
<style>
.box {
position: relative;
width: 500px;
height: 500px;
background-color: aqua;
}
.box1 {
position: absolute;
left: 250px;
top: 250px;
margin-top: -50px;
margin-left: -50px;
width: 100px;
height: 100px;
background-color: brown;
}
</style>
<body>
<div class="box">
<div class="box1"></div>
</div>
</body>
</html>
方法二:利用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>
</head>
<style>
.box {
position: relative;
width: 500px;
height: 500px;
background-color: aqua;
}
.box1 {
position: absolute;
margin: auto;
top: 0;
bottom: 0;
left: 0;
right: 0;
width: 100px;
height: 100px;
background-color: blue;
}
</style>
<body>
<div class="box">
<div class="box1"></div>
</div>
</body>
</html>
方法三:利用display:table-cell
<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>
</head>
<style>
.box {
width: 500px;
height: 500px;
display: table-cell;
vertical-align: middle;
text-align: center;
background-color: aqua;
}
.box1 {
display: inline-block;
width: 100px;
height: 100px;
background-color: black;
}
</style>
<body>
<div class="box">
<div class="box1"></div>
</div>
</body>
</html>
方法四:利用display: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>
</head>
<style>
.box {
display: flex;
justify-content: center;
align-items: center;
width: 500px;
height: 500px;
background-color: aqua;
}
.box1 {
width: 100px;
height: 100px;
background-color: red;
}
</style>
<body>
<div class="box">
<div class="box1"></div>
</div>
</body>
</html>
方法五:计算父盒子与子盒子的空间距离(不实用)
1:利用自身宽高减去父盒子的宽高 /2
方法六:利用transform位移
<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>
</head>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
.box {
position: relative;
width: 500px;
height: 500px;
background-color: aqua;
}
.box1 {
position: absolute;
transform: translate(-50%, -50%);
top: 50%;
left: 50%;
width: 100px;
height: 100px;
background-color: yellow;
}
</style>
<body>
<div class="box">
<div class="box1"></div>
</div>
</body>
</html>
通过上面的方法我们不难发现在盒子的居中里面我们用到了多次子绝父相所以定位也是前端基础中比较难也是比较重要的方法
最后送大家一句话:月薪过万,键盘敲烂!!!