<div class="middle-demo1"> <button>按钮</button></div>
.middle-demo1{ display: table-cell; height: 100px; //可以动态改变高度,这里只是演示 vertical-align: middle; border: 1px solid #666; }
浏览器支持情况:
http://caniuse.com/#search=table-cell
<div class="middle-demo2"> <div class="g-box"></div></div>
.middle-demo2{ position: relative; width: 200px; height: 200px; border: 1px solid #666; }.g-box{ position: absolute; top: 50%; width: 100px; height: 100px; margin-top: -50px; background-color: deepskyblue; }或者.g-box{ position: absolute; top: 50%; width: 100px; height: 100px; -webkit-transform: translateY(-50px); -moz-transform: translateY(-50px); -ms-transform: translateY(-50px); -o-transform: translateY(-50px); transform: translateY(-50px); background-color: deepskyblue; }
说明:要垂直居中的元素(g-box)必须是固定高度(js动态计算设置除外)。
transform的浏览器支持情况http://caniuse.com/#search=transform
<div class="middle-demo3"> <div class="g-box2"></div> <div class="g-box3"></div></div>
g-box3是需要垂直居中的元素
.middel-demo3{ position: relative; width: 200px; height: 200px; border: 1px solid #666; }.g-box2{ height: 50%; margin-bottom: -50px; }.g-box3{ height: 100px; background-color: deepskyblue; }
说明: 要垂直居中的元素(g-box3)必须是固定高度。
<div class="middle-demo4"> <div class="g-box4"></div></div>
.middle-demo4{ position: relative; width: 200px; height: 200px; border: 1px solid #666; }.g-box4{ position: absolute; top: 0; bottom: 0; margin-top: auto; margin-bottom: auto; width: 100px; height: 100px; background-color: deepskyblue; }
说明: 要垂直居中的元素(g-box4)可以不固定高度,浏览器支持情况IE8+,其他浏览器支持较好
<div class="middle-demo5"> <span>单行文本</span></div>
.middle-demo5{ height: 100px; line-height: 100px; border: 1px solid #666; }
说明: 对内部的块状元素无效
<div class="middle-demo6"> <p>单行文本</p> <p>多行文本</p></div>
.middle-demo6{ display: table-cell; vertical-align: middle; height: 200px; //容器可以不定高,这里只是演示 border: 1px solid #666; }
<div class="middle-demo7"> <span class="g-fix"></span> <button class="g-box7">行内元素</button></div>
.middle-demo7{ position: relative; width: 200px; height: 200px; border: 1px solid #666; }.g-fix{ display: inline-block; width:0; height: 100%; vertical-align: middle; }
说明: 浏览器支持情况http://caniuse.com/#search=inline-block