【CSS 布局】水平垂直方向居中
单行元素
<div class="container">
<div class="item"></div>
</div>
.container {
position: relative;
height: 400px;
border: 1px solid #ccc;
.item {
position: absolute;
width: 200px;
height: 200px;
left: 0;
right: 0;
bottom: 0;
top: 0;
margin: auto;
border: 1px solid #ccc;
}
}
- 方式二:relative 和 absolute(变种,适合于宽高固定)
.container {
position: relative;
height: 400px;
border: 1px solid #ccc;
.item {
position: absolute;
top: 50%;
left: 50%;
margin-top: -100px;
margin-bottom: -100px;
width: 200px;
height: 200px;
border: 1px solid #ccc;
}
}
.container {
display: flex;
height: 400px;
border: 1px solid #ccc;
.item {
width: 300px;
height: 300px;
border: 1px solid #ccc;
margin: auto;
}
}
.container {
display: flex;
height: 400px;
border: 1px solid #ccc;
justify-content: center;
align-items: center;
.item {
width: 300px;
height: 300px;
border: 1px solid #ccc;
}
}
.container {
display: flex;
height: 400px;
border: 1px solid #ccc;
justify-content: center;
.item {
width: 300px;
height: 300px;
border: 1px solid #ccc;
align-self: center;
}
}
多行元素
<div class="container">
<img src="./login.png" alt="" />
<p>欢迎访问我的个人博客 hhmax.xyz</p>
<button>按钮</button>
</div>
.container {
height: 400px;
border: 1px solid #ccc;
display: flex;
justify-content: center;
flex-direction: column;
align-items: center;
}