背景
常常我们会遇到让盒子在页面中水平垂直居中,例如在登录页面的时候,我们会让登录的盒子水平垂直居中在页面的中心。这个时候我们会有很多种方法去使得盒子居中。下面是我常用的三种方法:
- 定位+margin:auto
// css .aaa { width: 200px; height: 200px; position: relative; border: 1px solid #000; } .bbb { width: 100px; height: 100px; position: absolute; top: 0; left: 0; bottom: 0; right: 0; border: 1px solid #000; margin: auto; text-align: center; line-height: 100px; } // html <div class="aaa"> <div class="bbb">1</div> </div>
- flex布局法
// css .ccc { width: 200px; height: 200px; border: 1px solid #000; display: flex; justify-content: center; align-items: center; margin-left: 15px; } .ddd { width: 100px; height: 100px; border: 1px solid #000; text-align: center; line-height: 100px; } // html <div class="ccc"> <div class="ddd">2</div> </div>
- 定位移动法
// css .eee { width: 200px; height: 200px; border: 1px solid #000; position: relative; margin-left: 15px; } .fff { width: 100px; height: 100px; border: 1px solid #000; text-align: center; line-height: 100px; position: absolute; left: 50%; top: 50%; transform: translate(-50%, -50%); } // html <div class="eee"> <div class="fff">3</div> </div>
整体页面效果
<!DOCTYPE html>
<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>盒子水平垂直居中</title>
<style>
.box {
display: flex;
}
.aaa {
width: 200px;
height: 200px;
position: relative;
border: 1px solid #000;
}
.bbb {
width: 100px;
height: 100px;
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
border: 1px solid #000;
margin: auto;
text-align: center;
line-height: 100px;
}
.ccc {
width: 200px;
height: 200px;
border: 1px solid #000;
display: flex;
justify-content: center;
align-items: center;
margin-left: 15px;
}
.ddd {
width: 100px;
height: 100px;
border: 1px solid #000;
text-align: center;
line-height: 100px;
}
.eee {
width: 200px;
height: 200px;
border: 1px solid #000;
position: relative;
margin-left: 15px;
}
.fff {
width: 100px;
height: 100px;
border: 1px solid #000;
text-align: center;
line-height: 100px;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
</style>
</head>
<body>
<div class="box">
<div class="aaa">
<div class="bbb">1</div>
</div>
<div class="ccc">
<div class="ddd">2</div>
</div>
<div class="eee">
<div class="fff">3</div>
</div>
</div>
</body>
</html>