javascript - css 控制 div 始終水平垂直居中,這個div大小還不同
問題描述
css 控制加了一個統一類名的p,想讓他水平垂直居中顯示,但是這個p大小不一樣,css就不能寫固定,其他同學有什么好的思路沒
問題解答
回答1: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布局,使子元素水平垂直居中;另一種是使用絕對定位加transform移動位置。.flex { display: flex; align-items: center; justify-content: center;}
.one { position: absolute; left: 50%; top: 50%; transform: translate(-50%, -50%);}
傳送門
回答3:垂直居中:表格布局法 行內塊法絕對定位法視口居中基于flexbox 的方案
回答4:老生常談的問題,國外已經有人整理了各種情況的垂直居中:https://css-tricks.com/center...
甚至直接給你生成代碼,還考慮是否兼容IE:http://howtocenterincss.com/
也可以看看翻譯過的版本:https://github.com/chenjsh36/...
看完再也不怕各種垂直居中問題 23333
回答5:父元素加display:flex,align-items:center
回答6:上面使用彈性布局可以,但是不支持低級瀏覽器,可以使用絕對定位來使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;}回答7:
同樣建議 flex布局
回答8:各種彈層?各種計算?左右居中很簡單,只需要
margin:0 auto;即可,但是上下就稍微麻煩點了。雖然麻煩很多方式啊
1,js判斷,這個比較笨重,就不說了,簡單會js的朋友都會
2,disable:table. 這個需要兩個dom配合,不推薦,主要兼容性也一般
3,利用transfrom,這個如果不考慮兼容,不知道高度,極力推薦。大概方式如下:
.dom{ 寬自己定義 position: absolute; transform: translate(-50%, -50%); left: 50%; top: 50%;}知道寬度,不知道高度 推薦這個
4,如果知道寬高,那就不用上面了,因為上面不兼容啊,這個狂兼容,代碼如下:
.dom{ 寬高自己定義 position: absolute; margin: auto; top:0; right: 0; bottom:0; left: 0;}5,flex 布局,除了兼容,其他都沒問題。
<p class='mask'>
<p class='mask-con'> 這是文字信息</p>
</p>.mask{
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;
}.mask-con{
width: 200px;/*height: 90px;*/height: auto;background: #fff;font-size: 14px;padding: 20px;border-radius:10px;
}6, 如果考慮兼容====>請回看第一條。【都什么年代了 還考慮IE789 主要IE7 DOM1 支持都不大好,所以。。。】7,其他沒啥了。以上幾種絕對夠用了。有好的,請給予補充
回答9:父元素
{ position: relative;}
子元素
{position:absolute;top:50%;left:50%;transform:(-50%,-50%);}回答10:
再補充三個方法。
采用絕對或固定定位居中一個已知寬度和高度的元素:
.horizontal-and-vertical-center { width: 200px; height: 200px; position: fixed; top: 0; bottom: 0; left: 0; right: 0; margin: auto;}
采用 display: table 布局居中元素,支持不確定的寬度和高度,并且兼容 IE8+ 和其他現代瀏覽器:
.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 偽元素撐開行高 (AmazeUI 在 modal 組件中使用的辦法,并且支持不確定的寬度和高度, IE8+):
.am-modal { /* ... */ text-align: center; /* ... */}.am-modal:before { content: '200B'; 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; /* ... */}
