文本居中
text-align功能
設置或檢索對象中文本的左中右對齊方式
div居中
核心思想:absolute + 平移
平移方法1:top,left(div左上角頂點移到body中心) + margn-left,margin-top(div中心點移到body中心)
div頂點位於中心,再平移操作即可水平垂直居中
1 div { 2 position: absolute; 3 top: 50%; 4 left: 50%; 5 margin-left: -250px; 6 margin-top: -250px; 7 width: 500px; 8 height: 500px; 9 background-color: aqua; 10 border: 1px solid red; 11 }
缺陷:需要提前知道元素的尺寸。否則margin
負值的調整無法精確。此時,往往要借助JS獲得。
CSS3的興起,使得有了更好的解決方法,就是使用transform
代替margin
. transform
中translate
偏移的百分比值是相對於自身大小的
top,left(div左上角頂點移到body中心) + transform: translate(-50%, -50%)(div中心點移到body中心)
1 div { 2 ...... 3 transform: translate(-50%, -50%); 4 }
平移方法2: top、left、right、bottom(設定可用空間,相等即平分) + margin: auto(平分上下左右距離)
top = left = right = bottom即可,auto其計算值決定於可用空間
margin:auto=margin:auto auto auto auto
margin:0 auto=margin:0 auto 0 auto (沒設定上下空間,即上下相等不成立)
1 div { 2 background-color: darkorchid; 3 width: 200px; 4 height: 200px; 5 position: absolute; 6 top: 0; 7 left: 0; 8 right: 0; 9 bottom: 0; 10 margin: auto ; 11 }
水平居中(設定可用空間再居中)
1 position: absolute; 2 left: 0; 3 right: 0; 4 margin: auto ;
垂直居中(設定可用空間再居中)
1 position: absolute; 2 top: 0; 3 bottom: 0; 4 margin: auto ;