如何写一个上下左右都居中的正方形
方法一:使用flex+align-items+justify-content
<head>
<meta charset="UTF-8">
<title>
</title>
<style>
.father {
width: 100%;
height: 100%;
display: flex;
background-color: antiquewhite;
align-items: center;
justify-content: center;
}
.child {
width: 100px;
height: 100px;
background-color: aqua;
}
</style>
</head>
<body>
<div class="father">
<div class="child">
</div>
</div>
</body>
运行效果截图:
方法一:使用flex+margin
<style>
.father {
height: 100%;
display: flex;
background-color: antiquewhite;
}
.child {
width: 100px;
height: 100px;
background-color: red;
margin: auto;
}
</style>
</head>
<body>
<div class="father">
<div class="child"></div>
</div>
</body>
运行效果截图:
有关 flex 的知识详解可以参考这篇文章:点我