CSS implements vertical centering of elements
Vertical centering of elements will be discussed on a case-by-case basis for single-line elements and multi-line elements.
The vertical centering method of a single line of text with a determined height of the parent element is achieved by setting the height and line-height of the parent element to be consistent. .
HTML structure:
<div class="container"> Hello World!!!</div>
CSS style:
<style> .container{ height:100px; line-height:100px; background:#999; }</style>
The height of the parent element is uncertain The vertical centering of block-level elements such as text and pictures can be achieved by setting the same upper and lower padding values. This value does not need to be too large.
Multi-line text, pictures, and block-level elements all fall into this situation. There are two main methods for vertical centering.
Insert table (including tbody, tr, td) tags outside the element to be vertically centered, and set vertical-align: middle.
Also note that there is a property vertical-align in CSS for vertical centering, but this style will only take effect when the parent element is td or th.
HTML structure:
<body> <table> <tbody> <tr> <td class="wrap"> <div> <p>Hello World!!!</p> <p>Hello World!!!</p> <p>Hello World!!!</p> <p>Hello World!!!</p> <p>Hello World!!!</p> </div> </td> </tr> </tbody> </table></body>
CSS style:
table td{height:500px;background:#ccc}
Because the td tag sets vertical-align to middle by default, we don’t need to explicitly Set up.
In browsers such as chrome, firefox and IE8 or above, you can set the display of block-level elements to table-cell and activate vertical- align attribute, but note that IE6 and 7 do not support this style.
HTML structure:
<div class="container"> <div> <p>Hello World!!!</p> <p>Hello World!!!</p> <p>Hello World!!!</p> <p>Hello World!!!</p> <p>Hello World!!!</p> </div></div>
CSS style:
<style> .container{ height:300px; background:#ccc; display:table-cell; vertical-align:middle; }</style>
The advantage of this method is that there is no need to add redundant meaningless tags, but the disadvantages are also obvious , its compatibility is not very good and is not compatible with IE6 and 7.