A workaround for vertical centering of CSS

Source: Internet
Author: User

Horizontally centering an element in CSS is very simple: if it is an inline element, apply text-align:center to its parent element, and if it is a block-level element, apply margin:auto to it itself. However, if you want to center an element vertically, you may feel numb just by thinking about it.

Over the years, vertical centering has become the holy grail of CSS, and it is also a popular joke in the front-end development circle. The reason for this is that it has several characteristics:

1) It is an extremely common requirement.

2) Theoretically, it seems extremely simple.

3) In practice, it is often too hard, especially when it comes to elements that are not fixed in size.

Next, let's specify the simple use of these three methods.

First, the Code initialization

 Based on the following HTML code, we will center the DIV element of id= ' content ' in id= ' box ' div sheet vertically.


<body><div id= "box" >    <div id= "Content" > this is the element to be centered </div></div></body>
The basic styles are as follows:


#box {     margin:0;     padding:0;     width:500px;     height:500px;     Background: #4AC291;     font-size:100%;     Position:relative;} #content {     background: #655;     Color:white;     Text-align:center;     Line-height:2em;}

Second, the solution based on absolute positioning

If we want to use absolute positioning methods for vertical play, then it is required that the element has a fixed width and height, if there is no fixed width and height can not be achieved, because the need to take advantage of top and left values, To locate.

        #box {            margin:0;            padding:0;            width:500px;            height:500px;            Background: #4AC291;            font-size:100%;            position:relative;    necessary, because the following div is to be positioned according to this        }        #content {            background: #655;            Color:white;            Text-align:center;            Line-height:2em;            Position:absolute;   Set absolute positioning            top:50%;            left:50%;            Width:12em;            Height:2em;            Margin-top:-1em;    2/2=1            margin-left:-6em;    12/2=6      }

As shown, it is a fixed wide-height style effect.

This code essentially does a few things: Place the upper-left corner of the element in the right center of the viewport (or the nearest ancestor that has a positional attribute), and then use the negative margin to move it to the left and upward (the distance is equal to half its width), thus placing the positive center of the element in the center of the viewport. with the powerful Calc () function , this code can also dispense with the two-line declaration:


 #box {            margin:0;            padding:0;            width:500px;            height:500px;            Background: #4AC291;            font-size:100%;        position:relative;            } #content {background: #655;            Color:white;            Text-align:center;          Line-height:2em;            /*position:absolute;            top:50%;            left:50%;            Width:12em;            Height:2em;            Margin-top:-1em;            margin-left:-6em;*/Position:absolute;            Width:12em;            Height:2em;            Top:calc (50%-1em);      Left:calc (50%-6em); }

The biggest limitation of this method is that it requires that the width and height of the element be fixed. In general, the size of the element that needs to be centered is often determined by its content. If we can find the percentage value of an attribute as the resolution datum of the element's own width, then our problem will be solved! Unfortunately, for most CSS properties, including margin, the percentages are parsed on the basis of the dimensions of their parent elements.

Three, based on the solution of the viewport unit

Assuming that we do not want to use absolute positioning, we can still use the translate () technique to move the element in half its width and height, but in the absence of left and top, how do you place the top of this element in the center of the container?

Our first reaction is likely to be achieved using the percent value of the margin attribute, like this:


#content {  width:12em;  margin:50% Auto 0;  Transform:translatey (-50%);}

This code produces an outrageous effect. The reason is that the percent value of margin is the width of the parent element as the resolution datum. Yes, even for margin-top and Margin-bottom!

Fortunately, if you just want to center the element relative to the viewport, there is still hope. CSS values and units (third edition) define a new set of units, called viewport-related length units.

1) VW is associated with the viewport width. Contrary to the intuition of ordinary people, 1VW actually represents 1% of the width of the viewport, not 100%.

2) similar to VW, the 1VH represents 1% of the viewport height.

3) When the viewport width is less than the height, 1vmin equals 1vw, otherwise equal to 1VH.

4) When the viewport width is greater than the height, 1vmax equals 1vw, otherwise equal to 1VH.

Iv. Flexbox Method (the method described in this article)

The Flexbox (telescopic box) is designed specifically for this type of demand. The reason we're talking about other scenarios is that they are slightly better supported by browsers. In fact, the modern browser of the Flexbox support has been quite good.

We only need to write two lines of declaration: first to the parent element of the center element set Display:flex (in this case is the element), and then set the element itself we are familiar with the Margin:auto.


       #box {            Display:flex;            MIN-HEIGHT:50VH;            margin:0;            width:500px;            height:500px;            Background: #4AC291;        }        #content {            margin:auto;            Background: #655;            Color:white;        }

If the browser does not support Flexbox, the page render result looks just like our start chart (if width is set). It is completely acceptable, although it has no vertical centering effect.

Another benefit of FLEXBO is that it can also vertically center an anonymous container (that is, a text node that is not wrapped by a label).



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.