Set the top, bottom, left and right center for elements of known size
Product Manager: I have a 200 × 200 picture here. Please help me display it in the middle of the browser!
[Method 1] After positioning, set 0 at the top, bottom, left and right positions, and finally set the margin to auto!
.photo { width: 200px; height: 200px; position: fixed; top: 0; left: 0; right: 0; bottom: 0; margin: auto; }
[Method 2] After positioning, the upper and left positions are 50%. Finally, set the margin top to be half of the negative height, and the margin left to be half of the negative width. It can also be centered up, down, left and right!
.photo { width: 200px; height: 200px; position: fixed; top: 50%; left: 50%; margin-top: -100px; margin-left: -100px; }
Set the upper, lower, left and right center for elements of unknown size
Product Manager: I have another picture here, but I don't know the size of the goose. You should help me display it in the middle of the browser!
[Method 1] Whether you know the width and height of the element or not, you can directly set the upper and left positions to 50%, and then use the CSS3 attribute transform to make the element shift to the left half of its own, so as to achieve the upper, lower, left and right center!
.photo { position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%); }
[Method 2] Make this unknown size element horizontally and vertically centered relative to its parent element. Just set flex for the parent element, and then set the horizontal axis and vertical axis to center! (IE10 version and below are not supported)
.photo-box { /*Write the following code in the parent element of photo*/ display: flex; justify-content: center; align-items: center; }