css 控制加了一個(gè)統(tǒng)一類別名稱的p,想讓他水平垂直居中顯示,但是這個(gè)p大小不一樣,css就不能寫固定,其他同學(xué)有什麼好的思路沒
溫故而知新,可以為師矣。 博客:www.ouyangke.com
flex佈局吧
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style>
#main
{
width:220px;
height:300px;
border:1px solid black;
display:flex;
justify-content:center;
align-items:center;
}
#main p
{
}
</style>
</head>
<body>
<p id="main">
<p style="background-color:coral;">紅色</p>
</p>
</body>
</html>
一種是使用flex佈局,使子元素水平垂直居中;另一種是使用絕對(duì)定位加transform移動(dòng)位置。
.flex {
display: flex;
align-items: center;
justify-content: center;
}
.one {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
傳送門
老生常談的問題,國(guó)外已經(jīng)有人整理了各種狀況的垂直居中:https://css-tricks.com/center...
甚至直接給你產(chǎn)生程式碼,也考慮是否相容IE:http://howtocenterincss.com/
也可以看看翻譯過的版本:https://github.com/chenjsh36/...
看完再也不怕各種垂直居中問題 23333
上面使用彈性佈局可以,但是不支援低階瀏覽器,
可以使用絕對(duì)定位來使p垂直水平居中
p{
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
width: 620px;
height: 618px;
margin: auto;
padding: 30px 0;
box-sizing: border-box;
}
各種彈層?各種計(jì)算?左右居中很簡(jiǎn)單,只需要
margin:0 auto;
即可,但是上下就稍微麻煩點(diǎn)了。雖然麻煩很多方式啊
1,js判斷,這個(gè)比較笨重,就不說了,簡(jiǎn)單會(huì)js的朋友都會(huì)
2,disable:table. 這個(gè)需要兩個(gè)dom配合,不推薦,主要相容性也一般
3,利用transfrom,這個(gè)如果不考慮相容,不知道高度,極力推薦。大概方式如下:
.dom{
寬自己定義
position: absolute;
transform: translate(-50%, -50%);
left: 50%;
top: 50%;
}
知道這個(gè)寬度,不知道這個(gè)高度推薦
4,如果知道寬高,那就不用上面了,因?yàn)樯厦娌幌嗳莅。@個(gè)狂兼容,代碼如下:
.dom{
寬高自己定義
position: absolute;
margin: auto;
top:0;
right: 0;
bottom:0;
left: 0;
}
bottom:0;
<p class="mask-con">
這是文字信息
</p>
position: fixed;
top:0;
left: 0;
width: 100vw;
height: 100vh;
background: rgba(0,0,0,.5);
z-index: 1;
display: flex;
justify-content: center;
align-items: center;
width: 200px;
/*height: 90px;*/
height: auto;
background: #fff;
font-size: 14px;
padding: 20px;
border-radius:10px;
父元素
{
position: relative;
}
子元素
{
position:absolute;
top:50%;
left:50%;
transform:(-50%,-50%);
}
再補(bǔ)充三種方法。
採(cǎi)用絕對(duì)或固定定位居中一個(gè)已知寬度和高度的元素:
.horizontal-and-vertical-center {
width: 200px;
height: 200px;
position: fixed;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
}
採(cǎi)用 display: table
佈局居中元素,支援不確定的寬度和高度,並且相容於 IE8+ 和其他現(xiàn)代瀏覽器:
.table {
display: table;
width: 100%;
height: 100%;
position: fixed;
top: 0;
left: 0;
}
?
.cell {
display: table-cell;
vertical-align: center;
}
?
.horizontal-and-vertical-center {
width: 800px;
margin: 0 auto;
/* 如果不定寬度的話用 inline-block 并且外層 text-align: center */
}
:before
偽元素?fù)伍_行高 (AmazeUI 在 modal 組件中使用的辦法,並且支援不確定的寬度和高度, IE8+):
.am-modal {
/* ... */
text-align: center;
/* ... */
}
.am-modal:before {
content: "0B";
display: inline-block;
height: 100%;
vertical-align: middle
}
.am-modal-dialog {
position: relative;
display: inline-block;
vertical-align: middle;
margin-left: auto;
margin-right: auto;
/* ... */
}