Centering implementation of from:zhangxinxu.com absolute positioning element
If you want to ask how the CSS to achieve the central effect of absolute positioning elements, many people have the answer in mind.
The mainstream usage of good compatibility is:
. element { width:600px; height:400px; Position:absolute; left:50%; top:50%; Margin-top: -200px; /* Half of Height * /margin-left: -300px; /* Half of width */}
However, one obvious disadvantage of this approach is the need to know the dimensions of the elements in advance. Otherwise margin
, negative values cannot be adjusted accurately. At this time, often to use JS to obtain.
The rise of CSS3 makes it possible to have a better solution, which is to use transform
instead margin
. transform
The translate
percent value in the offset is relative to its size, so we can:
. element { width:600px; height:400px; Position:absolute; left:50%; top:50%; Transform:translate ( -50%, -50%); /* 50% is half of its size */}
Thus, regardless of the size of an absolutely positioned element, it is horizontally and vertically centered.
However, the problem is obvious and the compatibility is not good. ie10+ and other modern browsers are supported. The popularity of IE8 browsers in China is somewhat inappropriate (mobile Web development can be ignored).
In fact, the central implementation of the absolute positioning element has another method, which can be said to weigh the above size adaptive and compatibility of a scheme, the core of its implementation margin:auto
.
Third, Margin:auto to achieve the center of absolute positioning elements
First, let's look at the CSS code:
. element { width:600px; height:400px; Position:absolute; left:0; top:0; right:0; bottom:0; Margin:auto; /* Automatically center with this */}
Two key points of code:
- Position positioning of the upper and lower left and right
0
;
margin: auto
So, it's centered. The above code width: 600px
height: 400px
is only a schematic, you can change to another size, or do not set the size (need to be the image of the element itself contains dimensions), are centered. Very interesting ~ ~
You can get a hard click here: Margin:auto vertical centering with absolutely positioned elements demo
Click the button in the middle of the demo page to let the original frame static
absolute
, you can find it is horizontal vertical center.
I do not know you new skills get no?
By the way, the method ie8+ and other browsers are OK.
Absolute element, centered