編碼的世界 / 優質文選 / 生涯

最全CSS3實現水平垂直居中的10種方案


2021年11月25日
-   

/* 第一種方案 子元素高度可以設定也可以不設定*/
.app{
width: 500px;
height: 500px;
background: greenyellow;
display: flex;
align-items: center;
justify-content: center;
}
.app>div{
width: 100px;
height: 100px;
font-size: 20px;
background: blueviolet;
}
/* 第二種方案 子元素高度可以設定也可以不設定*/
.app{
width: 500px;
height: 500px;
background: greenyellow;
position: relative;
}
.app>div{
width: 100px;
height: 100px;
font-size: 20px;
background: blueviolet;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom:0;
margin: auto;
}
/* 第三種方案 子元素高度可以設定也可以不設定*/
.app{
width: 500px;
height: 500px;
background: greenyellow;
position: relative;
}
.app>div{
width: 100px;
height: 100px;
font-size: 20px;
background: blueviolet;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
}
/* 第四種方案 高度就是文字加line-height的高度 局限性在於必須裏邊的元素是inline否則不生效*/
.app{
width: 500px;
height: 500px;
background: greenyellow;
line-height: 500px;
text-align: center;
}
.app>div{
width: 100px;
font-size: 20px;
background: blueviolet;
display: inline;
}
/* 第五種方案 橫向利用margin auto,垂直還是利用定位和平移 也不用管裏邊元素的高度*/
.app{
width: 500px;
height: 500px;
background: greenyellow;
}
.app>div{
width: 100px;
font-size: 20px;
background: blueviolet;
position: relative;
top: 50%;
transform: translateY(-50%);
margin-left: auto;
margin-right:auto ;
}
/* 第六種方案 最不推薦的方案 通過計算padding 一旦內部元素改變了高度或者寬度,那就慘了*/
.app{
width: 500px;
height: 500px;
background: greenyellow;
box-sizing: border-box;
padding-left: 200px;
padding-top: 200px;
}
.app>div{
width: 100px;
height: 100px;
font-size: 20px;
background: blueviolet;
}
/* 第七中方案 本人沒用過,但是確實能實現 ,原來盒子的背景顏色被子元素覆蓋了,
我又試著添加了元素。有點意思。有時間可以研究下 vertical-align我一直很拒絕。這個方法也是解決多行文字垂直居中*/
.app{
width: 500px;
height: 500px;
background: greenyellow;
display: table;
text-align: center;
}
.app>div{
width: 100px;
height: 100px;
font-size: 20px;
background: blueviolet;
display: table-cell;
vertical-align: middle;
}
/* 第八種方案 單行文本好居中 就是讓文本的父元素的line-height和高度相同*/
.app{
width: 500px;
height: 500px;
background: greenyellow;
text-align: center;
line-height: 500px;
}
.app>div{
width: 100px;
height: 100px;
font-size: 20px;
background: blueviolet;
display: inline;
}
/* 第九種方案 多行文本垂直居中 這裏就不水平居中了。,。
除了歌詞水平居中之外,其他這麼的都不好看。
兩種方法:table法和不設高度法,我自己起的名字
以下是table 法
。*/
.app{
width: 500px;
height: 500px;
background: greenyellow;
display: table;
}
.app>div{
width: 100px;
height: 100px;
font-size: 20px;
background: blueviolet;
display: table-cell;
vertical-align: middle;
}
/* 不設高度法,更簡單 和其他的垂直居中一樣,上代碼就行
這個時候就實現多行文本居中了 然後至於換不換行加不加點就直接操作了
還能操作顯示幾行等等
這種方法的多行可操作強,否則小心後期難維護
*/
.app{
width: 500px;
height: 500px;
background: greenyellow;
display: flex;
align-items: center;
justify-content: center;
}
.app>div{
width: 100px;
font-size: 20px;
background: blueviolet;
/* overflow: hidden;
text-overflow: ellipsis;
word-break: break-all;
white-space: pre-line; */
}

 

熱門文章