<div class="middle-demo1"> <button>按钮</button></div>
.middle-demo1{ display: table-cell; height: 100px; //可以动态改变高度,这里只是演示 vertical-align: middle; border: 1px solid #666; }
Browser support:
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; }
Note: should be vertically centered The element (g-box) must be of fixed height (except for js dynamic calculation settings).
Browser support for transform http://caniuse.com/#search=transform
<div class="middle-demo3"> <div class="g-box2"></div> <div class="g-box3"></div></div>
g-box3 is an element that needs to be vertically centered
.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; }
Note: The element (g-box3) that needs to be vertically centered must be a fixed height.
<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; }
Explanation: Elements to be vertically centered (g-box4) can be The height is not fixed. The browser supports IE8 and other browsers have better support
<div class="middle-demo5"> <span>单行文本</span></div>
.middle-demo5{ height: 100px; line-height: 100px; border: 1px solid #666; }
Instructions : is invalid for internal block elements
<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; }
Instructions: Browser support http://caniuse.com/#search= inline-block