How to fully center with CSS only

Source: Internet
Author: User
We all know margin:0 auto; Style allows the element to be centered horizontally while margin:auto; But not vertically centered ... Until now. However, please note! To make the element absolutely centered, just declare the height of the element and append the following styles to do it:

. absolute-center {  margin:auto;  Position:absolute;  top:0; left:0; bottom:0; right:0;}

I'm not the first person to find out about this approach (but I dare call it "fully centered"), which can be a very common technique. But most of the articles that introduce vertical centering don't mention this approach

Simon provided a jsfiddle link, and the other methods were dwarfed by comparison. (Priit also mentions the same method in the Comments column). In-depth study of some, I used some keywords to find the record this method of three sites: site One, site II, site three.

I've never used this method before, and I want to try and see how amazing this "completely centered" approach is. Benefits:

Cross-browser, good compatibility (no hack, can take into account Ie8~ie10)

No special markings, more streamlined style

Adaptive layouts that use styles such as percentages and maximum minimum aspect

The padding value of the element is not considered when centered (nor does it need to use the box-sizing style)

Layout blocks can be freely resized

An IMG image can also be used

Also note:

Element height must be declared

recommended settings Overflow:auto; style to avoid overflow of elements, showing abnormal problems

This method does not work on the Windows Phone

Browser support: Chrome, Firefox, Safari, Mobile Safari, ie8-10. "Fully centered" tested to be perfectly applied to the latest versions of Chrome, Firefox, Safari, Mobile Safari, or even on ie8~ie10

Table

"Full centering" is not the only option in this article. To achieve vertical centering, there are other methods, each with its strengths. What to do depends on the browser you support and the structure of the existing tag. The following table will help you choose the method that best suits your needs.

Description

After studying the specifications and documentation, I summed up how "full centering" works:

In the normal document flow, Margin:auto; It means that the margin-top and margin-bottom of the set element are 0.

W3.org:?if ' margin-top ', or ' margin-bottom ' was ' auto ', their used value is 0.

2. Set the Position:absolute; Element becomes a block element and is detached from the normal document flow. The rest of the document is rendered as usual, and the elements do not appear to be in the same position. Developer.mozilla.org:?... an element which is positioned absolutely is taken out of the flow and thus takes up no space

3. Set the top:0; left:0; bottom:0; right:0; The block element of a style allows the browser to wrap a new box around it, so that the element fills its inner space relative to the parent element, which can be either a body tag or a set of position:relative; The container for the style. Developer.mozilla.org:? For absolutely positioned elements, "top", "right", "bottom" and "left" properties specify offsets from the edge of the Eleme NT ' s containing block (what's the element is positioned relative to).

4. When the element is set to a wide height, the browser blocks the element from filling up all the space, according to Margin:auto; requirements, recalculate, and wrap a new box. Developer.mozilla.org:?the margin of the [absolutely positioned] element is then positioned inside these offsets.

5. Since the block element is absolutely positioned and is out of normal document flow, the browser sets an equal value for Margin-top and margin-bottom before wrapping the box. W3.org:? If none of the three [top, bottom, height] is ' auto ': If both ' margin-top ' and ' margin-bottom ' is ' auto ', solve the Equa tion under the extra constraint that the both margins get equal values.? Aka:center The block vertically

Use "Full Center", intentionally follow the standard margin:auto; Style rendering, so it should work in a variety of browsers that are compatible with the standard.

Snap To

Align inside the container

With "full centering", you can fully center the element in a container that has a position:relative set! (center example, please go to the original English version)

. Center-container {  position:relative;}. absolute-center {  width:50%;  height:50%;  Overflow:auto;  Margin:auto;  Position:absolute;  top:0; left:0; bottom:0; right:0;}

The next example assumes that the following styles have been included and provides different attributes in a way that adds styles incrementally.

Center inside the viewable area

Do you want to center the content area within the viewable area? You can do this by setting the Position:fixed style and setting a higher z-index value.

. absolute-center.is-fixed {  position:fixed;  z-index:999;}

Description of Mobile Safari: If there is no container on the outside that sets Position:relative, the content area is centered on the center point of the height of the entire document, not the center of the height of the viewable area.

Offset value

If you need to add a fixed title, or other elements with offset style, you can directly put similar top:70px; Style is written into the style of the content area. Once the Margin:auto is declared; Style, the value of the property of the top left bottom of the content block is also computed at the same time.

You can use right:0 if you want the content block to be centered horizontally in the process close to the side side; Left:auto; Put content on the right, or use left:0; Right:auto; Paste the content on the left side.

. absolute-center.is-fixed {  position:fixed;  z-index:999;}

With response type

The biggest advantage of using absolute is that you can use the wide-height style with percentages perfectly! Even min-width/max-width or min-height/max-height can behave as expected.

Further add padding style, absolute style of the complete center will not be destroyed!

. absolute-center.is-responsive {  width:60%;   height:60%;  min-width:200px;  max-width:400px;  padding:40px;}

With overflow content

The content area height is greater than the viewable area or a position:relative container, and its contents may overflow the container or be truncated by the container. As long as the content area does not exceed the container (you can set the max-height:100% style if the content container is not reserved for padding), the scroll bar will be generated inside the container.

. Absolute-center.is-overflow {  Overflow:auto;}

Size Adjustable

Use a different style, or use JavaScript to resize the content area, and you don't have to recalculate it manually! If you set the resize style, you can even let the user adjust the size of the content area themselves. The "fully centered" method, regardless of how the content area changes size, will remain centered.

Set the properties at the beginning of the min-/max-to limit the size of the chunk without worrying about opening the container.

. absolute-center.is-resizable {  min-width:20%;  max-width:80%;  min-height:20%;  max-height:80%;  Resize:both;  Overflow:auto;}

If you do not set the Resize:both style, you can set the transition style to smoothly toggle between sizes. Be sure to remember to set the Overflow:auto style, since changing the size of the container aspect is likely to be less than the width of the content. The "Full Center" method is the only way to support the use of the Resize:both style.

Use Note:

You need to set Max-width/max-height to leave enough space in the content area, or it might overflow the container.

The Resize property does not support mobile browsers and IE8-10, and if the user experience is important, make sure that users can have alternative ways to change the size.

Using both the resize style and the transition will cause the user to start changing the size to produce a delay equal to the transition effect time.

Image

The image works equally well! Provide the corresponding class, and specify the style height:auto; , you get a responsive picture that changes size with the container.

Please note that Height:auto; Although the style is valid for a picture, if you do not use the ' variable height ' technique described later, it will cause the normal content area to stretch to fit the container length.

It is likely that the browser fills the image height value based on the rendered result, so in the tested browser, Margin:auto; The style is like declaring a fixed height value to work normally.

Html:

Css:

. absolute-center.is-image {  Height:auto;}. Absolute-center.is-image img {   width:100%;  Height:auto;}

Variable height

The "Full Center" method does need to declare the container height, but is highly affected by the max-height style, or it can be a percentage. This is ideal for responsive scenarios where you only need to set up with overflow content.

Another alternative is to set the display:table style centered, regardless of the length of the content. This approach can cause problems in some browsers (IE and Firefox, mostly). I wrote a MODERNIZR-based test at Ell Creative's friend Kalley, which can be used to check if the browser supports this centering scheme. This approach can now be incrementally enhanced.

Note: This approach can disrupt browser compatibility, and if the Modernizr test doesn't meet your needs, you might want to consider other implementations.

Incompatible with size-adjustable technology

The display:table is used in the FIREFOX/IE8, the content area is vertically oriented, and the horizontal direction is still centered.

Using display:table in IE9/10, the content area runs to the upper-left corner.

The content area in mobile safari is horizontally aligned, but if you use a percentage width, the horizontal direction is slightly off-center.

Javascript:

/* Modernizr Test for Variable Height Content */modernizr.teststyles (' #modernizr {display:table; height:50px; width:50 px Margin:auto; Position:absolute; top:0; left:0; bottom:0; right:0; } ', function (elem, rule) {  modernizr.addtest (' Absolutecentercontent ', Math.Round (WINDOW.INNERHEIGHT/2-25) = = = elem.offsettop);});

Css:

. absolutecentercontent. absolute-center.is-variable {  display:table;  Height:auto;}

Other methods

The "fully centered" approach is a good way to solve the problem of centering, and there are many other ways to meet different needs. The most common, recommended methods are negative margin values, transform method, Table-cell method, Inline-block method, and the present Flexbox method, which are discussed in detail in other articles, so this will only be mentioned slightly.

Negative margin value

This is probably the most common method. If you know the size of each element, set a negative margin value equal to half the width of the height (if you do not use the Box-sizing:border-box style, you also need to add a padding value), and then with top:50%; left:50%, the style causes the block element to be centered.

It is important to note that this is the only way to work under ie6-7 as expected.

. is-negative {        width:300px;        height:200px;        padding:20px;        Position:absolute;        top:50%; left:50%;        Margin-left: -170px; /* (width + padding)/2 */        margin-top: -120px;/* (height + padding)/2 */}

Benefits:

Browser compatibility is very good, even support ie6-7

The required number of encodings is very low

Also note:

This is a non-responsive method, cannot use a percentage size, and cannot set the maximum minimum value for min-/max-.

Content may go beyond the container

You need to reserve space for padding, or you need to use the Box-sizing:border-box style.

Transform method

As well as the benefits of the "full centering" method, it is simple and effective, while supporting variable heights. Specify Transform:translate ( -50%,-50%) and top:50% with the vendor prefix for the content, left:50%, and style to center the content block.

. is-transformed {   width:50%;  Margin:auto;  Position:absolute;  top:50%; left:50%;  -webkit-transform:translate ( -50%,-50%);      -ms-transform:translate ( -50%,-50%);          Transform:translate ( -50%,-50%);}

Benefits:

Highly variable content

Small amount of code

Also note:

IE8 not supported

Need to write vendor prefix

Will conflict with other transform styles

Problems with edge and font rendering in some cases

Table-cell method

This is probably the best approach, because the height can change with the content, and the browser support is not bad. The main drawback is that additional tags are generated, and each element that needs to be centered requires three additional HTML tags.

Html:

<div class= "Center-container is-table" >  <div class= "Table-cell" >    <div class= "Center-block" >    <!--CONTENT--    </div>  </div></div>

Css:

. center-container.is-table {display:table;}. Is-table. Table-cell {  Display:table-cell;  Vertical-align:middle;}. Is-table. Center-block {  width:50%;  margin:0 Auto;}

Benefits:

Highly variable content

Content overflow can automatically open the parent element height

Good browser compatibility

Also note:

Additional HTML tags are required

Inline-block method

Urgently needed method: The Inline-block method is centered. The basic method is to use Display:inline-block, vertical-align:middle styles and pseudo elements to center the content block in the container. My implementation uses a few new tricks that I can't see anywhere else to solve some of the problems.

The width of the content area declaration cannot be greater than the width of the container's 100% minus 0.25em. It's like an area with long text. Otherwise, the content area is pushed to the top, which is why you use: after Pseudo-class. Use: Before pseudo-class will make the element have 100% size!

If the content block needs to occupy as much horizontal space as possible, you can add max-width:99% to the large container, style, or use the Max-width:calc (100%–0.25EM) style with the browser and container width in mind.

This approach is the same as most of the Table-cell benefits, but at first I gave up this method because it was more like a hack. In spite of this, browser support is good and proven to be a popular method.

Html:

<div class= "Center-container is-inline" >  <div class= "Center-block" >    <!--CONTENT  -- </div></div>

Css:

. center-container.is-inline {   text-align:center;  Overflow:auto;} . Center-container.is-inline:after,.is-inline. Center-block {  display:inline-block;  Vertical-align:middle;} . Center-container.is-inline:after {  content: ';  height:100%;  Margin-left: -0.25em; /* to offset spacing. May vary by font */}. Is-inline. Center-block {  max-width:99%;/* Prevents issues with long content causes the content Block to being pushed to the top * //  * MAX-WIDTH:CALC (100%-0.25em)/* Only for ie9+ */}

Benefits:

Highly variable content

Content overflow can automatically open the parent element height

Browser compatibility is good, can even adjust support IE7

Also note:

Additional containers required

Dependent on Margin-left: -0.25em style, do horizontal centering, need to adjust for different font size

The width of the content area declaration cannot be greater than the width of the container 100% minus 0.25em

Flexbox method

The future direction of CSS is to use the Flexbox design to solve common problems like vertical centering. Note that Flexbox has more than one way of centering, and he can also be used to sort the columns and solve the weird layout problems.

. Center-container.is-flexbox {  display:-webkit-box;  Display:-moz-box;  Display:-ms-flexbox;  Display:-webkit-flex;  Display:flex;  -webkit-box-align:center;     -moz-box-align:center;     -ms-flex-align:center;  -webkit-align-items:center;          Align-items:center;  -webkit-box-pack:center;     -moz-box-pack:center;     -ms-flex-pack:center;  -webkit-justify-content:center;          Justify-content:center;}

Benefits:

Content can be any high-width, overflow can also perform well

Can be used for various advanced layout techniques

Also note: Ie8-9 is not supported

Need to write style on body, or need extra container

Requires a variety of vendor prefixes compatible with modern browsers

There may be potential performance issues

The final recommendation

Each technology has its own benefits, depending on the browser you support and the structure of the existing tags. Please use the chart above to help you choose the method that best suits your needs.

"Fully centered" method is simple and convenient, prompt and timely. Where negative margin values were used previously, they can be centered using absolute. No tedious mathematical calculations, no additional labels, and can be changed at any time.

If your site needs variable-height content, and you're looking for browser compatibility, try Table-cell and Inline-block technology, and if you want to try something new, use Flexbox and enjoy the benefits of this advanced technology.

  • 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.