css絕對定位居中


技術參考:https://www.php.cn/css-tutorial-409962.html

1.兼容性不錯的主流css絕對定位居中的用法:

1 .conter{
2     width: 600px; height: 400px;
3     position: absolute; left: 50%; top: 50%;
4     margin-top: -200px;    /* 高度的一半 */
5     margin-left: -300px;    /* 寬度的一半 */
6 }

注意:這種方法有一個很明顯的不足,就是需要提前知道元素的尺寸。否則margin負值的調整無法精確。此時,往往要借助JS獲得。

2.css3的出現,使得有了更好的解決方法,就是使用transform代替margin. transform中translate偏移的百分比值是相對於自身大小的,可以這樣實現css絕對定位居中:

1 .conter{
2     width: 600px; height: 400px;
3     position: absolute; left: 50%; top: 50%;
4     transform: translate(-50%, -50%);    /* 50%為自身尺寸的一半 */
5 }

3.margin:auto實現絕對定位元素的居中(上下左右均0位置定位;margin: auto):

1 .conter{
2     width: 600px; height: 400px;
3     position: absolute; left: 0; top: 0; right: 0; bottom: 0;
4     margin: auto;    /* 有了這個就自動居中了 */
5 }

4.使用css3盒模型:flex布局實現css絕對定位居中。這種情況是在不考慮低版本瀏覽器的情況下可以使用:

1 .conter{
2   display:flex;
3   justify-content: space-between;
4   align-items: center;    
5 }
6 
7 <div class="conter">
8     <div></div>
9 </div>

元素.conter的子元素會居中定位


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM