居中
1. 单行文本居中
单反文本居中效果 |
---|
单行文本居中
|
<style>
/** 方式一
.box {
height: 150px;
width: 150px;
background-color: #e3e3e3;
text-align: center;
line-height: 150px;
}
*/
/** 第二种方式
.box {
height: 150px;
width: 150px;
background-color: #e3e3e3;
display: flex;
justify-content: center;
align-items: center;
}
*/
/* 第三种方式
.box {
height: 150px;
width: 150px;
background-color: #e3e3e3;
display: flex;
justify-content: center;
flex-wrap: wrap;
align-content: center;
}
*/
</style>
<div class="box">
这是一行文字
</div>
2. 多行文本居中
多放文本居中 |
---|
多行文本居中
|
<style>
/** 第一种方式
.box {
height: 150px;
width: 150px;
background-color: #e3e3e3;
display: flex;
justify-content: center;
align-items: center;
}
*/
/* 第二种方式
.box {
height: 150px;
width: 150px;
background-color: #e3e3e3;
display: flex;
justify-content: center;
flex-wrap: wrap;
align-content: center;
}
*/
.box {
height: 150px;
width: 150px;
background-color: #e3e3e3;
display:table-cell;
vertical-align: middle;
}
</style>
<div class="box">
这是多行文字这是多行文字这是多行文字这是多行文字这是多行文字这是多行文字
</div>
3. 块级元素居中
块级元素居中效果 |
---|
块级元素居中
|
<style>
/** 方式一
.box {
height: 200px;
width: 200px;
background-color: skyblue;
display: flex;
justify-content: center;
align-items: center;
}
.box .inner {
height: 100px;
width: 100px;
background-color: purple;
}
*/
/** 方式二
.box {
height: 200px;
width: 200px;
background-color: skyblue;
position: relative;
}
.box .inner {
height: 100px;
width: 100px;
background-color: purple;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
*/
// 第三种方式算是一种奇淫技巧吧
.box {
height: 200px;
width: 200px;
background-color: skyblue;
position: relative;
}
.box .inner {
height: 100px;
width: 100px;
background-color: purple;
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
margin: auto;
}
</style>
<div class="box">
<div class="inner"></div>
</div>