惱人的垂直置中 vertical-align
這是個討人厭又傷腦筋的問題 !! 每次需求要做垂直置中效果,幾乎都用 js 去算 box 對齊位置,是個非常緩慢沒效率的方法 >"<,對不起我太笨了!!
方法1: (FaceBook 也是用此排法)
<style> #box { display: table; } #box div { display: table-cell; width: 200px; height: 300px; text-align: center; border: solid 1px orange; vertical-align: middle; } #box span { width: 50px; height: 80px; background: yellow; display: inline-block; } </style> <div id="box"> <div><span></span></div> </div>
table 排版法!! - http://jsfiddle.net/LWvPU/
方法2:
<style> #wrap_box { width: 200px; height: 300px; text-align: center; border: solid 1px orange; } #wrap_box:before { content: ''; display: inline-block; width: 0; height: 100%; vertical-align: middle; } #box { width: 50px; height: 80px; background: yellow; display: inline-block; vertical-align: middle; } </style> <div id="wrap_box"> <div id="box"> </div> </div>
偽元素對齊法! - http://jsfiddle.net/uV4hS/
方法3:
<style> #wrap_box { width: 200px; height: 300px; text-align: center; border: solid 1px orange; position: relative; } #box { width: 50px; height: 80px; background: yellow; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); } </style> <div id="wrap_box"> <div id="box"> </div>
transform 置中法 (感謝太略提供 -2015/02/03) - http://jsfiddle.net/p27ndsxy/
方法4:
<style> #wrap_box { background: orange; height: 100vh; width: 100%; display: inline-flex; align-items: center; justify-content:center; } #box { background: yellow; width: 50%; height: 30px; } </style> <div id="wrap_box"> <div id="box"></div> </div>
flex方式 - https://jsfiddle.net/0q8ha6hx/