作为一个小白菜鸟前端,每次写布局都会烦很久。今天记录一下四种盒子居中的方法~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
第一种
<!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>
.box {
width: 400px;
height: 400px;
background-color: aqua;
}
.box1 {
width: 200px;
height: 200px;
background-color: wheat;
}
/* 第一种 */
.box{
position: relative;
}
.box1{
position: absolute;
inset: 0;
margin: auto;
}
</style>
</head>
<body>
<div class="box">
<div class="box1"></div>
</div>
</body>
</html>
第二种
<!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>
.box {
width: 400px;
height: 400px;
background-color: aqua;
}
.box1 {
width: 200px;
height: 200px;
background-color: wheat;
}
/* 第二种 */
.box{
display: flex;
}
.box1{
margin: auto;
}
</style>
</head>
<body>
<div class="box">
<div class="box1"></div>
</div>
</body>
</html>
第三种
<!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>
.box {
width: 400px;
height: 400px;
background-color: aqua;
}
.box1 {
width: 200px;
height: 200px;
background-color: wheat;
}
/* 第三种 */
.box{
display: grid;
place-items: center;
}
</style>
</head>
<body>
<div class="box">
<div class="box1"></div>
</div>
</body>
</html>
第四种
<!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>
.box {
width: 400px;
height: 400px;
background-color: aqua;
}
.box1 {
width: 200px;
height: 200px;
background-color: wheat;
}
/* 第四种 */
.box{
display: flex;
align-items: center;
justify-content: center;
}
</style>
</head>
<body>
<div class="box">
<div class="box1"></div>
</div>
</body>
</html>