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

CSS垂直居中 #5

Open
liangfengbo opened this issue Aug 1, 2019 · 0 comments

Comments

@liangfengbo
Copy link
Owner

commented Aug 1, 2019

垂直居中

<ul class="parent">
    <li class="child">垂直居中</li>
</ul>

方法一

  • 设置父元素为表格单元,再加个vertical-align: middle;
  • 优点:简单
  • 缺点:ie6,7不支持
.parent {
    dispaly: table-cell;
    vertical-align: middle;
}

.child {
}

方法二

  • 设置父元素为相对定位
  • 然后设置子元素为绝对定位,设置top为50%;再设置 transform:translateY(-50%);
  • 优点:居中元素不会对其他的产生影响
  • 缺点:transfrom兼容性问题
.parent {
    position: relative;
}

.child {
    position: absolute;
    top: 50%;
    transform: translateY(-50%);
}

方法三

  • 父元素设置弹性盒子,再设置对齐 align-items:center;
  • 优点:简单快捷
  • 缺点:兼容性
.parent {
    display: flex;
    align-items: center;
}
.child {
}

方法四

  • 父元素设置高度,再使用line-height来垂直居中
.parent {
    height: 100px;
    line-height: 100px;
}

.child {
}

方法五

  • 将父元素设置为网格布局,再设置align-items:center;align-content:center;
 .parent {
    display:grid;
    align-items:center;
    /*align-content:center;*/
}

.child {
}

方法六:

  • 将父元素设置为网格布局,子元素再设置align-self:center;或者margin: auto 0
 .parent {
    display:grid;
    
}

.child {
    align-self:center;
}

方法七:

  • 首先设置父元素为网格布局,然后子元素设置align-self: center; 或者margin: auto 0;
.parent {
    display: grid;
}

.child {
    align-self: center;
    /**margin: auto 0;**/
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
1 participant
You can’t perform that action at this time.