CSS achieves horizontal vertical center of div, and horizontal center of cssdiv

Source: Internet
Author: User

CSS achieves horizontal vertical center of div, and horizontal center of cssdiv

There are many solutions for implementing center. Here we will introduce the solutions for pure CSS to use absolute with margin.

1. Fixed div width and height

width: 400px;height: 200px;position: absolute;top: 50%;left: 50%;margin-top: -100px;margin-left: -200px;

Margin-top is-(height/2), and margin-left is-(width/2 ). Of course, you do not need to use margin, that is, top is calc (100%-height)/2, left is calc (100%-width)/2, but it is recommended that you do not use it without calc.

2. The div width and height are not fixed.

width: 50%;height: 50%;position: absolute;top: 0;right: 0;bottom: 0;left: 0;margin: auto;

Note: this applies to situations where the width and height need to be specified, such as using percentages or using js to dynamically modify them. Otherwise, it may be treated as 100%.

You can also use translate () instead of margin, as shown below:

width: 50%;height: 50%;position: absolute;top: 50%;left: 50%;transform: translateX(-50%) translateY(-50%);

 3. CSS3 fixed width and high-level vertical center

Justify-content: center;/* sub-element horizontal center */align-items: center;/* sub-element vertical center */display:-webkit-flex;

Add the parent element to vertically center the child element horizontally.

Related Article

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.