Completely centered using only CSS_html/css_WEB-ITnose

WBOY
Release: 2016-06-24 12:07:57
Original
1103 people have browsed it

We all know that margin:0 auto; style can center the element horizontally, but margin: auto; cannot center it vertically...until now. However, please note! If you want the element to be absolutely centered, you only need to declare the height of the element and append the following styles:

.Absolute-Center {

   margin : auto ;

   position : absolute ;

   top : 0 ; left : 0 ; bottom : 0 ; right : 0 ;

.Absolute-Center {

margin : auto ;

position : absolute ;

top : 0 ; left : 0 ; bottom : 0 ; right : 0 ;

I am not the first person to discover this method (but I still dare to call it "completely centered") ”), it may be a very common technique. But most articles about vertical centering don’t mention this method. If I hadn't read the comments on this article, I wouldn't have even discovered this method.

In the comment column of the above article, Simon provided a link to jsFiddle, and other methods pale in comparison. (Priit also mentioned the same method in the comments column). After some in-depth research, I used certain keywords to find three websites documenting this method: Site 1, Site 2, and Site 3.

所用样式

支持的浏览器

是否 响应式

内容溢出后的样式

resize:both

高度可变

主要缺陷

Absolute

现代浏览器&IE8

会导致容器溢出

是*

‘可变高度’的特性不能跨浏览器

负margin值

所有

带滚动条

大小改变后不再居中

不具有响应式特性,margin值必须经过手工计算

Transform

现代浏览器&IE9

会导致容器溢出

妨碍渲染

Table-Cell

现代浏览器&IE8

撑开容器

会加上多余的标记

Inline-Block

现代浏览器&IE8 &IE7*

撑开容器

需要使用容器包裹和hack式的样式

Flexbox

现代浏览器&IE10

会导致容器溢出

需要使用容器包裹和厂商前缀(vendor prefix)
Having never used this method before, I wanted to try it and see how magical this "completely centered" method is. Benefits: Cross-browser, good compatibility (no hack required, can take into account IE8~IE10) No special tags, the style is more streamlined and adaptive layout, you can use percentage and maximum and minimum height and width and other styles to center without considering the padding of the element. Value (no need to use box-sizing style) The layout block can be freely adjusted in size. IMG images can also be used . At the same time, note: must declare the element. It is highly recommended to set the overflow:auto; style to avoid element overflow and abnormal display. Problem This method does not work on Windows Phone Browser support: Chrome, Firefox, Safari, Mobile Safari, IE8-10. "Completely Centered" has been tested and can be used perfectly in the latest versions of Chrome, Firefox, Safari, and Mobile Safari, and can even run on IE8~IE10 Comparison Table "Completely Centered" is not part of this article the only option in . There are other ways to achieve vertical centering, each with its own advantages. The approach you take depends on the browsers you support and the structure of your existing tags. The comparison table below can help you choose the method that best suits your needs.
Style used Supported browsers Whether it is responsive Style after content overflows resize:both Highly variable Major flaws
Absolute Modern Browser & IE8 is will cause the container to overflow is Yes* The 'variable height' feature does not work across browsers
Negative margin value All No With scrollbar No longer centered after size change No Does not have responsive features, margin value must be After manual calculation
Transform Modern browser&IE9 Yes will cause the container to overflow Yes Yes Hinders rendering
Table-Cell Modern browsers & IE8 Yes Open container No Yes Add redundant tags
Inline-Block Modern browsers&IE8 &IE7* Yes Open the container No Yes Requires container wrapping and hacky styles
Flexbox Modern browsers & IE10 is will cause Container overflow is is requires the use of container packaging and vendor prefix )
Description

After studying the specifications and documents, I summarized the working principle of "complete centering":

1. In ordinary document flow, margin: auto; means to set the margin- of the element. top and margin-bottom are 0.

 W3.org If 'margin-top', or 'margin-bottom' are 'auto', their used value is 0.

 2. Elements with position: absolute; set will Become a block element and break away from the normal document flow. The rest of the document renders as usual, and the elements appear to be no longer in their original positions. Developer.mozilla.org …an element that is positioned absolutely is taken out of the flow and thus takes up no space

 3. top: 0; left: 0; bottom: 0; right: 0; The styled block element will cause the browser to wrap a new box around it, so the element will fill the internal space of its relative parent element. This relative parent element can be the body tag, or an element with position: relative; style container. Developer.mozilla.org For absolutely positioned elements, the top, right, bottom, and left properties specify offsets from the edge of the element's containing block (what the element is positioned relative to).

 4. After setting the width and height, the browser will prevent the element from filling all the space, recalculate it according to the requirements of margin: auto;, and wrap it with 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 separated from the normal document flow, the browser wraps the box Previously, margin-top and margin-bottom were set to equal values. W3.org If none of the three [top, bottom, height] are 'auto': If both 'margin-top' and 'margin-bottom' are 'auto', solve the equation under the extra constraint that the two margins get equal values.?AKA: center the block vertically

Using "fully centered" intentionally complies with the standard margin: auto; style rendering regulations, so it should work in various browsers that are compatible with the standard.

Alignment Alignment within the container

Using "completely centered", you can completely center the element in a container with position: relative set! (For centered examples, please go to the original English text to view)

.Center-Container {

   position : relative ;

.Absolute-Center {

   width : 50% ;

   height : 50% ;

   overflow : auto ;

   margin : auto ;

   position : absolute ;

   top : 0 ; left : 0 ; bottom : 0 ; right : 0 ;

.Center-Container {

position : relative ;

.Absolute-Center {

width : 50% ;

height : 50% ;

.Absolute-Center.is-Fixed {

   position : fixed ;

   z-index : 999 ;

overflow : auto ; margin : auto ; position : absolute ; top : 0 ; left : 0 ; bottom : 0 ; right : 0 ;
The following examples will assume that the following styles have been included, and will provide different features by gradually adding styles. Center within the visible area Want to center the content area within the visible area? You can do it by setting the position: fixed style and setting a higher z-index value.
.Absolute-Center.is-Fixed { position : fixed ; z-index: 999;

Instructions for the mobile version of Safari : If there is no container with position: relative set outside, the content area will be centered around the entire The document is centered based on the height center point of the document, rather than the height center point of the visible area.

Offset value

If you need to add a fixed title or other elements with offset styles, you can directly write a style like top: 70px; into the style of the content area. Once the margin: auto; style is declared, the top left bottom right attribute value of the content block will also be calculated at the same time.

If you want the content block to remain horizontally centered while being close to the side, you can use right: 0; left: auto; to make the content stick to the right, or use left: 0; right: auto; to make the content stick to the right. The content is posted on the left.

.Absolute-Center.is-Fixed {

   position : fixed ;

   z-index : 999 ;

.Absolute-Center.is-Fixed {

position : fixed ;

z-index: 999;

.Absolute-Center.is-Responsive {

   width : 60% ;

   height : 60% ;

   min-width : 200px ;

   max-width : 400px ;

   padding : 40px ;

With responsive Use absolute The biggest benefit is that you can perfectly use the width and height styles with percentages! Even min-width/max-width or min-height/max-height can perform as expected.

If you add a padding style further, the absolute centering will not be destroyed at all!

.Absolute-Center.is-Responsive {

.Absolute-Center.is-Overflow {

   overflow : auto ;

width : 60% ;

height : 60% ;

min-width : 200px ;

max-width : 400px ;

padding : 40px ;

.Absolute-Center.is-Resizable {

   min-width : 20% ;

   max-width : 80% ;

   min-height : 20% ;

   max-height : 80% ;

   resize: both ;

   overflow : auto ;

With overflow content The height of the content area is greater than the visible area or a container with position: relative, its content may Will overflow the container, or be truncated by the container. As long as the content area does not exceed the container (if no padding is reserved for the content container, you can set the max-height: 100%; style), then scroll bars will be generated within the container.
.Absolute-Center.is-Overflow { overflow : auto;
Resizable Use other styles, or use JavaScript to resize the content area, too No need to manually recalculate! If the resize style is set, the user can even adjust the size of the content area by themselves. "Completely centered" method, no matter how the content area changes size, it will remain centered. Setting the attributes starting with min-/max- can limit the size of the block 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 switch between sizes smoothly. Be sure to remember to set the overflow: auto style, because the height and width of the container after changing the size are likely to be smaller than the height and width of the content. The "completely centered" method is the only method that supports using the resize: both style.

Usage Note:

You need to set max-width/max-height to leave enough space for the content area, otherwise the container may overflow. The resize attribute does not support mobile browsers and IE8-10. If user experience is important, make sure users have other alternatives to change the size. Using a resize style and a transition at the same time will cause a delay equal to the transition effect time when the user starts to change the size. Images

Images work too! Provide the corresponding class and specify the style height: auto; to get a responsive image that changes size as the container changes size.

Please note that although the height: auto; style is effective for images, if the 'variable height technique' introduced later is not used, it will cause the normal content area to stretch to fit the container. length.

It is very likely that the browser fills the image height value based on the rendering result, so in the tested browsers, the margin: auto; style works normally as if it declares a fixed height value.

HTML:

< img src = "http://placekitten.com/g/500/200" alt = "" />

< img src = "http://placekitten.com/g/500/200" alt = "" />

 CSS:

.Absolute-Center.is-Image {

   height : auto ;

.Absolute-Center.is-Image img {

   width : 100% ;

   height : auto ;

.Absolute-Center.is-Image {

height : auto ;

.Absolute-Center.is-Image img {

width : 100% ; height : auto ;
Variable height The "completely centered" method does need to declare the container height, but the height is affected by the max-height style and can also be a percentage. This is very suitable for responsive solutions, just set up the overflow content.

Another alternative is to set the display: table style to center, regardless of the length of the content. This method can cause problems in some browsers (mainly IE and Firefox). My friend Kalley at ELL Creative wrote a test based on Modernizr that can be used to check whether the browser supports this centering scheme. Now this approach can do progressive enhancement.

Important points to note: This method will break browser compatibility. If Modernizr testing cannot meet your needs, you may need to consider other implementation solutions.

is incompatible with resizable technology.

/* Modernizr Test for Variable Height Content */

Modernizr.testStyles( '#modernizr { display: table; height: 50px; width: 50px; 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);

});

Use display: table in Firefox/IE8. The content area is vertically upward and still centered horizontally. When display: table is used in IE9/10

, the content area will move to the upper left corner. The content area in Mobile version

Safari

is aligned horizontally, but if a percentage width is used, it will be slightly off-center horizontally.

.absolutecentercontent .Absolute-Center.is-Variable {

   display : table;

   height : auto ;

 Javascript:
/* Modernizr Test for Variable Height Content */ Modernizr.testStyles( '#modernizr { display: table; height: 50px; width: 50px; 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 "completely centered" method is a good way to solve the centering problem, and there are many other methods that can meet different needs. The most common and recommended methods are negative margin value, transform method, table-cell method, inline-block method, and the now emerging Flexbox method. These methods are introduced in depth in other articles, so they will only be mentioned briefly here.

Negative margin value

This is perhaps the most commonly used method. If you know the size of each element, set a negative margin value equal to half the width and height (if you do not use the box-sizing: border-box style, you also need to add a padding value), and then match top: 50%; left: 50% ; style will center the block element.

It should be noted that this is the only way to work under IE6-7 as expected.

tr>

.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 */

.is-Negative {

     width: 300px;

height: 200px;

padding: 20px;

position: absolute;

.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% );

top: 50%; left: 50%; 🎜> margin- left : -170px ; /* (width padding)/2 */

    margin-top : -120px ; /* (height padding)/2 */

Advantages:

Browser compatibility is very good, even supports IE6-7. Very little coding is required

At the same time, note:

This is a very The responsive method cannot use percentage size, nor can it set the maximum and minimum values ​​of min-/max-. The content may exceed the container and space needs to be reserved for padding, or the box-sizing: border-box style needs to be used. The transform method

has the same benefits as the "completely centered" method, is simple and effective, and supports variable height. You can center the content block by specifying the transform: translate(-50%,-50%) and top: 50%; left: 50%; styles with the vendor prefix for the content.

.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% );
Advantages: Highly variable content and small amount of code Also note: IE8 is not supported. The manufacturer prefix needs to be written, which will conflict with other transform styles. In some cases, there will be problems with edge and font rendering. table-cell method This may be the best method, because the height can change with the content, browsing Server support isn't bad either. The main drawback is that it generates extra tags, three extra HTML tags for each element that needs to be centered. HTML:
                                                          ;

CSS:

tr>

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

.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: The content height is variable and the content overflow can automatically expand the parent element. The height is good for browser compatibility

At the same time, note:

requires additional HTML tag inline-block method

Urgently needed method: inline-block method to center. The basic approach is to use display: inline-block, vertical-align: middle styles and pseudo-elements to center the content block in the container. My implementation uses several new tricks not seen elsewhere to solve some problems.

< div class = "Center-Container is-Inline" >

   < div class = "Center-Block" >

    

  

The declared width of the content area cannot be greater than 100% of the container minus the width of 0.25em. Like an area with long text. Otherwise, the content area will be pushed to the top, which is why the :after pseudo-class is used. Using the :before pseudo-class will make the element 100% size!

If the content block needs to occupy as much horizontal space as possible, you can add the max-width: 99%; style to the large container, or use max when considering the browser and container width. -width: calc(100% ? 0.25em) style.

This method has most of the same benefits as table-cell, but I initially gave up on this method because it was more like a hack. Regardless of this, browser support is great and the method is proving to be very popular.

.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 be pushed to the top */

   /* max-width: calc(100% - 0.25em) /* Only for IE9 */

HTML:
< div class = "Center-Container is-Inline" > < div class = "Center-Block" >
 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 be pushed to the top */ /* max-width: calc(100% - 0.25em) /* Only for IE9 */

Benefits:

The content height is variable and the content overflow can automatically expand the parent element. The height is good browser compatibility and can even be adjusted to support IE7

At the same time, note:

requires additional The container relies on the margin-left: -0.25em style to achieve horizontal centering. It needs to be adjusted for different font sizes. The declared width of the content area cannot be greater than 100% of the container, minus the width of 0.25em. Flexbox method

CSS Future The direction of development is to use Flexbox design to solve common problems such as vertical centering. Please note that Flexbox has more than one way to center. It can also be used to divide columns and solve 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 ;

.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 ;
Advantages: The content can be any height and width, and it can perform well even if it overflows. It can be used in various Advanced layout techniques Also note: IE8-9 is not supported Styles need to be written on the body, or additional containers are required. Various vendor prefixes are required to be compatible with modern browsers. There may be potential performance issues. Final suggestions Each technique has its own benefits, and the approach you take depends on the browsers you support and the structure of your existing tags. Please use the comparison table provided above to help you choose the method that best suits your needs. The "completely centered" method is simple, convenient, fast and timely. Wherever negative Margin values ​​were used before, Absolute can be used to center. No tedious math, no extra labels, and the size can be changed at any time. If your website requires variable-height content while taking into account browser compatibility, you can try table-cell and inline-block technologies. If you want to try something new, you can use Flexbox and enjoy it. the benefits of advanced technology. Original link: codepen.io Translation: Bole Online - Emjie
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template