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

元素水平、垂直居中 #9

Open
juzhiyuan opened this issue Jun 20, 2018 · 0 comments
Open

元素水平、垂直居中 #9

juzhiyuan opened this issue Jun 20, 2018 · 0 comments
Labels

Comments

@juzhiyuan
Copy link
Owner

juzhiyuan commented Jun 20, 2018

固定宽高、绝对定位元素

.element {
  width: 100px;
  height: 100px;
  position: absolute;
  left: 50%;
  top: 50%;

  // 高度一半
  margin-top: -50px;
  // 宽度一半
  margin-left: -50px;
}

缺点

  • 需要知道元素宽高,否则无法精确调整**margin(可通过 JS 获取)

固定宽高、绝对定位元素

.element {
  width: 100px;
  height: 100px;
  position: absolute;
  left: 50%;
  top: 50%;

  // 50% 为自身尺寸一半
  transform: translate(-50%. -50%);
}
  • transform 偏移的百分比值是相对自身大小的

margin: auto

.element {
  width: 100px;
  height: 100px;
  position: absolute;

  left: 50%;
  top: 50%;
  right: 0;
  bottom: 0;
  margin: auto;
}

注意

  • 上下左右均0位置定位
  • margin: auto
  • 可以不设置尺寸(需要是图片这种自身包含尺寸的元素)

Flex

<div class="container">
  <div class="box">一些元素</div>
</div>
.container {
  display: flex;
  justify-content: center;
  align-items: center;
}

行内元素

父级元素设置text-aligin: center;即可

Grid

.container {
  display: grid;
  grid-template-columns: 50px;
  justify-content: center;
}
@juzhiyuan juzhiyuan added duplicate This issue or pull request already exists CSS and removed duplicate This issue or pull request already exists labels Jun 20, 2018
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