Use absolute positioning to align the top of the element with the center line, and move the element up to 50%. This should be hard to understand. The principle can be illustrated in the following figure:
The code is as follows: |
Copy code |
* Code implementation: * Set the width and height. The parent node is position: relative. CSS is written as follows: */ . Selector { Position: absolute; top: 50% ;. Margin-top:-half of the height of an element; }
|
Instance
The code is as follows: |
Copy code |
<! DOCTYPE html> <Html lang = "en-US"> <Head> <Meta charset = "UTF-8"/> <Title> vertical center </title> <Style> * {Margin: 0; padding: 0 ;} Body {font-family: consolas; padding: 20px ;} Img, p {border: 1px dotted # bbb; padding: 5px ;} P {margin-bottom: 10px ;} A {text-decoration: none ;} . Wrap { Width: 500px; height: 300px; border: 3px solid # ddd; margin: 0 auto; padding: 20px; display: table; * Position: relative; } . Hack { Display: table-cell; vertical-align: middle; * Position: absolute; * top: 50%; } . Cnt { * Position: relative; * top:-50%; } </Style> </Head> <Body> <Div class = "wrap"> <Div class = "hack"> <Div class = "cnt">
<P> The content here is www.111cn.net. </P> <P> <A href = "http //: www.111cn.net" title = "return: vertical center implementation methods"> Return: vertical center implementation methods & raquo; </a> </P> </div> </Div> </Div>
</Body> </Html> |