Long ago understand that when the element is fixed width and height, the horizontal vertical high Center method can set the negative value of the margin to the center, this negative value is half the width and height of the element, such as the width of the height is 100px, then use Margin-left:-50px;margin-top: -50px such a way of writing. But what if the width and height of this element are expressed as a percentage?
If you use a percentage to set the width, the previous negative method has not been used, which we found in a small trick, is to use CSS3 in the transform of the translate conversion properties. Here's a code example:
HTML code
<div class= "center" > You can try to change the size of the browser, this element is still horizontal vertical center Oh! </div>
CSS Code
. center{position:absolute;top:50%;left:50%;width:50%;height:30%;p Adding:20px;text-align:center;background: #393 ; color: #fff; transform:translate (-50%,-50%);}
View Demo
If you directly copy the code is not available, add the-webkit-transform or-moz-transform prefix, in the case I used the-prefix-free this plugin, the plug-in function is not required to enter-moz-and-webkit-these prefixes.