CSS transform to make a percentage wide and high layout element horizontally vertically centered

Source: Internet
Author: User

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

<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%;padding:20px;text-align:Center;background:#393;Color:#fff;Webkit-transform:Translate ( -50%, -50%);-moz-transform:Translate ( -50%, -50%);Transform:Translate ( -50%, -50%);}

CSS transform to make a percentage wide and high layout element horizontally vertically centered

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.