css居中(上下左右居中,垂直居中,水平居中)
阿新 • • 發佈:2021-10-11
初始樣式
.outside {
width: 200px;
height: 200px;
background-color: red;
}
.inside {
width: 100px;
height: 100px;
background-color: rgb(231, 255, 15);
}
<div class="outside">
<div class="inside">
我是被居中的盒子
</div>
</div>
上下左右居中
方式一:已知寬高差,position+top or position+margin
在初始的樣式上新增以下樣式
.outside{
position:relative;
}
.inside {
position:absolute;
top: 50px;
left: 50px;
}
/*或者*/
.inside {
position:absolute;
margin-top: 50px;
margin-left: 50px;
}
方式二:未知寬高差,position+top/left+transform
在初始的樣式上新增以下樣式
.outside{ position:relative; } .inside { position:absolute; top: 50%; left: 50%; transform:translate(-50%,-50%); }
方式三:未知寬高差,display:flex
在初始的樣式上新增以下樣式
.outside{
display:flex;
justify-content: center;
align-items: center;
}
左右居中
在初始的樣式上新增以下樣式
.inside{
margin: 0 auto;
}
上下居中
在初始的樣式上新增以下樣式
.outside{
display: table-cell;
vertical-align: middle;
}
行內元素垂直水平居中
初始樣式
<h1 class="text">line-height和height的使用</h1> .text{ height: 100px; background-color: chartreuse; }
在初始的樣式上新增以下樣式
.text{
/* 垂直居中,line-height與height值一致 */
line-height: 100px;
/* 水平居中 */
text-align: center;
}