一、行内元素的居中方法
1、单行文本垂直居中
.center {
// 完全可以不设置高度
// height: 20px;
line-height: 20px;
}
2、多行文本垂直居中——vertical-align
<div class="box">
<div class="center">
啦啦啦啦啦啦
</div>
</div>
<style>
.box {
background-color: orange;
line-height: 200px;
width: 300px;
}
.center {
background-color: green;
line-height: 20px;
display: inline-block;
vertical-align: middle;
}
</style>
复制代码
2、.table-cell(不是很常用)
.box {
height: 23px;
display: table-cell;
vertical-align: middle;
}
行内元素水平居中
text-align: center;
二、块级元素居中
水平居中
margin: 0 auto;
垂直居中
1、.position(居中元素宽高固定)父绝子相
.box {
position: relative;
}
.center {
position:absolute;
width: 200px;
height: 200px;
top:0;
bottom:0;
left:0;
right:0;
margin: auto;
}
2、vertacal-align
<div class="box">
<div class="assist"></div>
<div class="center">
啦啦啦啦啦
</div>
</div>
<style>
.box {
background-color: orange;
height: 200px;
width: 500px;
text-align: center;
}
.center {
background-color: green;
width: 150px;
display: inline-block;
vertical-align: middle;
}
.assist {
display: inline-block;
height: 100%;
vertical-align: middle;
}
</style
3、position配合margin
<div class="box">
<div class="center">
啦啦啦啦啦啦
</div>
</div>
<style>
.box {
background-color: orange;
height: 200px;
width: 500px;
position: relative;
}
.center {
background-color: green;
width: 150px;
height: 50px;
position:absolute;
top:50%;
left:50%;
margin-left: -75px;
margin-top: -25px;
}
</style>
4、position配合transform
<div class="box">
<div class="center">
啦啦啦啦啦啦啦啦啦啦
</div>
</div>
<style>
.box {
background-color: orange;
height: 200px;
width: 500px;
position: relative;
}
.center {
background-color: green;
width: 150px;
position:absolute;
top:50%;
left:50%;
transform: traslate(-50%, -50%);
}
</style>
5、flex
.box {
display: flex;
align-items: center;
justify-content: center;
}
本文详细介绍了如何使用各种方法实现行内元素的垂直和水平居中,包括单行文本、多行文本和块级元素的居中处理,涵盖了`vertical-align`、`position`、`flexbox`等技术。同时,提供了实例代码和常见居中策略的实践应用。
380

被折叠的 条评论
为什么被折叠?



