The problem of horizontal center and vertical centering in HTML. (fixed height and height variable)

Source: Internet
Author: User

In the process of layout, we have to center on some elements, I believe, we have no problem in the horizontal center, is to use

margin:0 auto; and text centered text-align:center.

Here's what I want to tell you about overall centering (horizontal and vertical centering),

Here, I first told you that I used the absolute positioning method,

I'm going to make a box for you to observe directly, as follows

The outer and inner boxes are squares with edges of 300px and 100px respectively.

We're going to center the inner frame. (At this point, the inner frame height is fixed)

1 when height is fixed.

In general, we will do the code directly,

Position:absolute;

top:50%;

left:50%;

So at first glance, there is no problem, but after the operation, we will find

The inner box is not centered, and the result is that we ignore the inner frame as a shape body, not a line.

To solve this problem, we want to use the negative value of margin, through negative values, the whole is moved again, and the value of the move is half the length of the border.

The code is as follows:

Position:absolute;

top:50% margin-top:-50px;

left:50% margin-left:-50px;

The effect is as follows:

the use of negative values allows the label to be close to the parent element, so that we can achieve the center effect.

2 in case of high uncertainty .

In fact, the principle is the same , but in the height of uncertainty, we can not select the height of half, just change the code part:

Position:absolute;

top:50%;

left:50%;

Transform:translate (-50%,-50%);

This completes the centering effect as well.

Let's go and try.

The problem of horizontal center and vertical centering in HTML. (fixed height and height variable)

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.