We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
如何用 css 让一个元素垂直居中
Centering in the Unknown
The text was updated successfully, but these errors were encountered:
<div class="container"> <div class="center-me"> center me! </div> </div>
先把元素的左上角定位到中间,然后通过 margin 调整位置
margin
.center-me { position: absolute; left: 50%; right: 50%; width: 20em; height: 8em; margin-left: 10em; margin-top: 4em; }
缺点:要求元素的宽高是固定的,
.center-me { position: absolute; left: 50%; right: 50%; transform: translate(-50%, -50%); }
据说在某些浏览器中会导致元素的显示变模糊,因为元素可能会被放置在半个像素上,这个问题可以用 transform-style: preserve-3d 修复
transform-style: preserve-3d
Sorry, something went wrong.
css3 定义了一套新的单位:视口相关的长度单位
使用视口高度,可以直接将元素调整到视口中央
.center-me { width: 20em; margin: 50vh auto 0; /* 直觉上是 50「%」,然而这个 % 是相对于父元素的宽度 */ transform: translateY(-50%); }
缺点:只适用于视口中居中
可能是最优雅的解决方案了
.container { display: flex; } .center-me { margin: auto; }
或者仅仅设置父元素
.container { display: flex; justify-content: center; align-items: center; }
No branches or pull requests
如何用 css 让一个元素垂直居中
Reference
Centering in the Unknown
The text was updated successfully, but these errors were encountered: