Home >Web Front-end >HTML Tutorial >Completely centered using only CSS_html/css_WEB-ITnose
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:
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) |
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 ) |
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 containerUsing "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)
position : relative ; .Absolute-Center { width : 50% ; height : 50% ;
|
.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 valueIf 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.
position : fixed ; z-index: 999;
|
.Absolute-Center.is-Responsive { width : 60% ; height : 60% ; min-width : 200px ; max-width : 400px ; padding : 40px ; |
If you add a padding style further, the absolute centering will not be destroyed at all!
.Absolute-Center.is-Responsive {
height : 60% ; min-width : 200px ; max-width : 400px ; padding : 40px ;
|
.Absolute-Center.is-Overflow { overflow : auto; |
.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. ImagesImages 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:
|
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 ; |
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); }); |
, the content area will move to the upper left corner. The content area in Mobile version
Safariis 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 ; |
/* 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); }); |
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 valueThis 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.
width: 300px; height: 200px; padding: 20px; position: absolute;
margin-top : -120px ; /* (height padding)/2 */
| tr>
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 {
|
; |
CSS:
.is-Table .Table-Cell { display : table-cell ; vertical-align : middle ; .is-Table .Center-Block { width : 50% ; margin : 0 auto ;
| tr>
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" >
div > div > |
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 */ |
< div class = "Center-Container is-Inline" > < div class = "Center-Block" > div > div > |
.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 IE7At 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 methodCSS 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.
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 ; |