最近自己没事写一些前端的东西玩玩儿,经常会有将div中的元素进行垂直居中或者水平居中的需求,所以这里记录一下自己最常用的方法:
效果显示:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.div_body{
background-color: bisque;
width: 350px;
height: 450px;
border-radius: 10px;
/* 1.将容器设置 display 为flex */
display: flex;
/* 2.设置垂直居中 */
align-items: center;
/* 3.设置水平居中 */
justify-content: center;
}
.login{
background-color: red;
height: 20px;
}
</style>
</head>
<body>
<div class="div_body">
<div class="login">
这是测试div
</div>
</div>
</body>
</html>