Skip to content
New issue

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

垂直居中的几种实现方式 #1

Open
sunhengzhe opened this issue Jul 14, 2017 · 3 comments
Open

垂直居中的几种实现方式 #1

sunhengzhe opened this issue Jul 14, 2017 · 3 comments
Labels

Comments

@sunhengzhe
Copy link
Member

sunhengzhe commented Jul 14, 2017

如何用 css 让一个元素垂直居中

Reference

Centering in the Unknown

@sunhengzhe sunhengzhe added the css label Jul 14, 2017
@sunhengzhe
Copy link
Member Author

基于绝对定位

<div class="container">
    <div class="center-me">
        center me!
    </div>
</div>

先把元素的左上角定位到中间,然后通过 margin 调整位置

.center-me {
    position: absolute;
    left: 50%;
    right: 50%;
    width: 20em;
    height: 8em;
    margin-left: 10em;
    margin-top: 4em;
}

缺点:要求元素的宽高是固定的,

使用 translate!

.center-me {
    position: absolute;
    left: 50%;
    right: 50%;
    transform: translate(-50%, -50%);
}

据说在某些浏览器中会导致元素的显示变模糊,因为元素可能会被放置在半个像素上,这个问题可以用 transform-style: preserve-3d 修复

@sunhengzhe
Copy link
Member Author

基于视口

css3 定义了一套新的单位:视口相关的长度单位

  • vw 与 视口宽度 相关。1vw 代表视口宽度的 1%
  • vh 与 vw 类似,1vh 代表视口高度的 1%
  • vmin 和 vmax 很形象,当视口宽度大于视口高度时(比如 PC),1vmax 等于 1vw,1vmin 等于 1vh。视口宽度小于视口高度时就反过来

使用视口高度,可以直接将元素调整到视口中央

.center-me {
    width: 20em;
    margin: 50vh auto 0; /* 直觉上是 50「%」,然而这个 % 是相对于父元素的宽度 */
    transform: translateY(-50%);
}

缺点:只适用于视口中居中

@sunhengzhe
Copy link
Member Author

基于 flexbox

可能是最优雅的解决方案了

.container {
    display: flex;
}

.center-me {
    margin: auto;
}

或者仅仅设置父元素

.container {
    display: flex;
    justify-content: center;
    align-items: center;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant