CSS居中絕對定位元素的方法,有不少種,下面是我收集的幾種瀏覽器
1,div寬度未知1spa
<body> <div style="position: absolute; left: 50%;"> <div style="position: relative; left: -50%; border: dotted red 1px;"> 沒有寬度<br /> 照樣居中,嘿嘿嘿 </div> </div> </body>
demo:https://jsfiddle.net/skura23/0123wmsg/.net
2,div寬度未知2code
<div class="outer"> <div class="inner">居中<br/>蓄力中</div> </div> .outer { position: relative; /* or absolute */ /* unnecessary styling properties */ margin: 5%; width: 80%; height: 500px; border: 1px solid red; } .inner { position: absolute; left: 50%; top: 50%; transform: translate(-50%, -50%); /* unnecessary styling properties */ max-width: 50%; text-align: center; border: 1px solid blue; }
demo: http://jsfiddle.net/skura23/6xo11zwv/210/orm
ps:此方法適合ie8以上的瀏覽器blog
3,div寬度已知get
<body> <div> <div id="content"> 居中蓄力中 </div> </div> </body> #content { position: absolute; left: 0; right: 0; margin-left: auto; margin-right: auto; width: 100px; /* 要設定寬度 */ }
demo:https://jsfiddle.net/skura23/rk3qfvv2/1/it
--------------------------------------------------io
後面有其餘的方法的話,會繼續添加form