(1)單行文本的居中
水平居中:text-align:center;
垂直居中:line-height:xxpx;
例子
<div class=“div1”><p>單行文字</p></div>
.div1{
width:300ox;
margin:20px;
background:#000;
text-align:center;
}
.div1 p{
color:#fff;
font-size:16px;
line-height:300px;
}
(2)多行文本的垂直居中
1、使用display:table來實(shí)現(xiàn)
display:table;使塊狀元素成為一個(gè)塊級(jí)表格
display: table-cell;子元素設(shè)置成表格單元格
vertical-align: middle;使表格內(nèi)容居中顯示,實(shí)現(xiàn)垂直居中的效果
例子
<div class=“div1”><p>多行文字</p></div>
.div1{
position: relative;
width:300px;
height:300px;
margin:20px auto;
background:#000;
text-align: center;
display:table;
}
.div1 p {
coLor:#fff;
font-size:16px;
display:table-cell;
vertical-align:middle;
}
2、使用absolute與transform配合實(shí)現(xiàn)
position:absolute; 首先給文本絕對(duì)定位;
left:50%;top:50%; 讓文本距離盒子左邊和上邊分別為50%,
transform:translate(-50%,-50%); 再向左向上平移自己高度和寬度的50%,實(shí)現(xiàn)居中效果。
例子
.div1{
position: relative; /*讓元素相對(duì)定位*/
width:300px;
height:300px;
margin:20px auto;
background:#000;
text-align:center;
}
.div1 p{
color:#fff;
font-size:16px;
line-height:25px;
width:100%;
position:absolute; /*讓元素絕對(duì)定位*/
left:50%; top:50%;
transform:translate(-50%,-50%);
}
3、使用flex實(shí)現(xiàn)
display: flex; 將其定義為彈性容器
align-items:center; 垂直對(duì)齊居中
justify-content:center; 水平對(duì)齊居中
例子
.div1 {
position:relative;
width:300px;
height:300px;
margin:20px auto;
background: #000;
text-align:center;
display: flex;
align-items:center;
justify-content:center;
}
.div1 p{
coLor:#fff;
font-size:16px;
line-height:25px;
}
遠(yuǎn)近互聯(lián)前端小王整理發(fā)布,希望能對(duì)學(xué)習(xí)技術(shù)的你有所幫助
遠(yuǎn)近互聯(lián)專業(yè)提供網(wǎng)站建設(shè)、APP開發(fā)、網(wǎng)站優(yōu)化、外貿(mào)網(wǎng)站SEO、微信運(yùn)營(yíng)的品牌整合營(yíng)銷服務(wù)讓客戶通過網(wǎng)絡(luò)品牌建立與網(wǎng)絡(luò)傳播提高業(yè)績(jī)。






