• Welcome to Baben's blog that year. I'm glad to meet you at the right age!
  • Due to the theme, the QQ login partner displays the default avatar in the comments. Please go to the personal center to upload the avatar again.

Css centers divs or elements of unknown size horizontally and vertically

Code Notes barben Five years ago (2019-08-06) 3061 views 0 comments

Set the top, bottom, left and right center for elements of known size

[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

[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; }


Eight blogs that year, we have been
If the author does not indicate that it is an original article, please indicate the link and source of this article for reprinting
Css centers divs or elements of unknown size horizontally and vertically- https://www.barben.cn/code/562.html
Like( eight )
Post my comments
Cancel comment
expression Mapping Bold Strike through Center Italic

You need to bring your nickname and email with you in the review of Eight Books that year!

  • Nickname (required)
  • Email (required)
  • website