1、给父盒子开启flex布局
display: flex;
2、在父盒子中设置justify-content属性,实现水平居中
justify-content: center;
3、在父盒子中设置align-items属性,实现垂直居中
align-items: center;
4、完整代码:
<!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>
<style>
* {
margin: 0;
padding: 0;
}
.box {
width: 600px;
height: 80px;
background-color: #f40;
margin: 50px auto;
display: flex;
justify-content: center;
align-items: center;
}
</style>
</head>
<body>
<div class="box">
<p>flex布局1</p>
<p>flex布局2</p>
</div>
</body>
</html>
5、不设置flex布局和设置flex布局前后的对比如下:
不设置flex布局:
设置flex布局: