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

垂直居中 #3

Open
AILINGANGEL opened this issue May 30, 2019 · 1 comment
Open

垂直居中 #3

AILINGANGEL opened this issue May 30, 2019 · 1 comment

Comments

@AILINGANGEL
Copy link
Owner

AILINGANGEL commented May 30, 2019

1.知道元素的宽高

<div class="div1">
  <div class="div2"></div>
</div>

方法一: absolute + 负margin(负margin可以让元素左移)

  • top和left设置成百分比是相对于父元素的
  • 将margin-left和margin-top设置成自身宽高的一半并变成负数
.div1 {
  width: 100vw;
  height: 100vh;
  background-color: pink;
  position: relative;  //这里<div class="div1">
  <div class="div2"></div>
</div>
}

.div2 {
  width: 200px;
  height: 200px;
  background-color: black;
  position: absolute;  //这里
  top: 50%;  //这里
  left: 50%;  //这里
  margin-left: -100px;  //这里
  margin-top: -100px;  //这里
}

方法二: absolute + top.bottom.left.right都为0 + margin为auto

.div1 {
  width: 100vw;
  height: 100vh;
  background-color: pink;
  position: relative; //这里
}

.div2 {
  width: 200px;
  height: 200px;
  background-color: black;
  position: absolute; //这里
  top:0; //这里
  left: 0; //这里
  right: 0; //这里
  bottom: 0; //这里
  margin: auto; //这里
}

方法三: absolute + top和left用calc来计算

.div1 {
  width: 100vw;
  height: 100vh;
  background-color: pink;
  position: relative;
}

.div2 {
  width: 200px;
  height: 200px;
  background-color: black;
  position: absolute;
  top: calc(50% - 100px);
  left: calc(50% - 100px);
}

2.不知道元素的宽高

方法一: absolute + top 和left + transform

  • translate中的百分比是相对于元素自身的
.div1 {
  width: 100vw;
  height: 100vh;
  background-color: pink;
  position: relative;
}

.div2 {
  width: 50%;
  height: 100px;
  background-color: black;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

方法二: 父元素display: table-cell 并设置text-align:center和vertical-align:middle,为了让text-align:center生效,设置子元素为display: inline-block;

.div1 {
  width: 100vw;
  height: 100vh;
  background-color: pink;
  display: table-cell; //这里
  text-align: center; //这里
  vertical-align: middle; //这里
}

.div2 {
  width: 50%;
  height: 100px;
  background-color: black;
  display: inline-block; //这里
}

方法三: 利用flex, justify-content, align-items

.div1 {
  width: 100vw;
  height: 100vh;
  background-color: pink;
  display: flex; //这里
  align-items: center; //这里
  justify-content: center; //这里
}

.div2 {
  width: 50%;
  height: 100px;
  background-color: black;
}
@AILINGANGEL
Copy link
Owner Author

记住了,在布局中,只有vertical-align设置居中的时候值是middle,其他的都是center!!!!

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

No branches or pull requests

1 participant