在css3出來以前,我們要想讓元素既水平居中又要垂直居中只有一個辦法(我能想到的),就是通過js計算,把它們定位到屏幕中間位置。這方法比較笨,也麻煩。
下面兩種方式,可以讓元素快速定位到屏幕中間。
flex布局
<style> .flex-mask { display: flex; position: fixed; z-index: 1; top: 0; left: 0; bottom: 0; right: 0; align-items: center; // 垂直居中 justify-content: center; // 水平居中 background: rgba(0,0,0,.5); } .flex-box { width: 500px; height: 300px; background-color: #fff; border-radius: 10px; } </style> <!-- 元素 --> <p class="flex-mask"> <p class="flex-box"></p> </p>
使用translate
<style> .transform-box { position: fixed; z-index: 2; top: 50%; left: 50%; width: 300px; height: 150px; background-color: red; border-radius: 10px; transform: translate(-50%, -50%); } </style> <p class="transform-box"></p>
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com