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

水平垂直居中 #19

Open
sihai00 opened this issue Jul 30, 2019 · 0 comments
Open

水平垂直居中 #19

sihai00 opened this issue Jul 30, 2019 · 0 comments
Assignees
Labels

Comments

@sihai00
Copy link
Owner

sihai00 commented Jul 30, 2019

让一个 div 水平垂直居中

<div class="parent">
  <div class="child"></div>
</div>

绝对定位

第一种

div.parent {
    position: relative; 
}
div.child {
    position: absolute; 
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);  
}

第二种

div.parent {
    position: relative; 
}
div.child {
    width: 50px;
    height: 10px;
    position: absolute;
    left: 0;
    top: 0;
    right: 0;
    bottom: 0;
    margin: auto;
}

第三种:子元素定宽高

div.parent {
    position: relative; 
}
div.child {
    width: 50px;
    height: 10px;
    position: absolute;
    top: 50%;
    left: 50%;
    margin-left: -25px;
    margin-top: -5px;
}

弹性布局

第一种

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

第二种

div.parent{
  display:flex;
}
div.child{
  margin:auto;
}

网格布局

div.parent {
    display: grid;
}
div.child {
    justify-self: center;
    align-self: center;
}

基线对齐

第一种:

div.parent {
    font-size: 0;
    text-align: center;
    height: 500px;
    line-height: 500px;
}
div.child{
    width: 100px;
    height: 100px;
    display: inline-block;
}

第二种:

div.parent {
    font-size: 0;
    text-align: center;
    &::before {
        content: "";
        display: inline-block;
        width: 0;
        height: 100%;
        vertical-align: middle;
    }
}
div.child{
  display: inline-block;
  vertical-align: middle;
}

表格对齐

div.parent {
  display: table-cell;
  text-align: center;
  vertical-align: middle;
}
div.child {
  display: table-cell
}
@sihai00 sihai00 added the css label Jul 30, 2019
@sihai00 sihai00 self-assigned this Jul 30, 2019
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