【CSS 布局】水平垂直方向居中
单行元素
<div class="container">
<div class="item"></div>
</div>
- 方式一:relative 和 absolute
.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;
}
}
- 方式三:flex 和 margin
.container {
display: flex;
height: 400px;
border: 1px solid #ccc;
.item {
width: 300px;
height: 300px;
border: 1px solid #ccc;
margin: auto; /* 关键点 */
}
}
- 方式四:flex
.container {
display: flex;
height: 400px;
border: 1px solid #ccc;
justify-content: center;
align-items: center;
.item {
width: 300px;
height: 300px;
border: 1px solid #ccc;
}
}
- 方式五:flex
.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;
}
文章来源地址https://www.toymoban.com/news/detail-636696.html
文章来源:https://www.toymoban.com/news/detail-636696.html
到了这里,关于【CSS 布局】水平垂直方向居中的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!