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

垂直居中 #13

Open
wengjq opened this issue Jul 27, 2017 · 0 comments
Open

垂直居中 #13

wengjq opened this issue Jul 27, 2017 · 0 comments
Labels

Comments

@wengjq
Copy link
Owner

wengjq commented Jul 27, 2017

1、已知宽高元素的水平垂直居中

绝对定位与负边距实现。利用绝对定位,将元素的top和left属性都设为50%,再利用margin边距,将元素回拉它本身高宽的一半,实现垂直居中。代码如下:

#container {
    position:relative;
}
 
#div {
    position:absolute;
    width: x;
    height: y;
    top: 50%;
    left: 50%;
    margin: -x / 2 0 0 -y / 2;
}

2、未知宽高元素的水平垂直居中

2.1 方法一

也是利用绝对定位与margin。代码如下:

#container {
    position:relative;
}

#div {
    position: absolute;
    margin: 0 auto;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
}

2.2 方法二

当要被居中的元素是内联元素的时候,可以巧妙的将父级容器设置为display:table-cell,配合text-align:center和vertical-align:middle即可以实现水平垂直居中。代码如下:

#container {
    display:table-cell;
    text-align:center;
    vertical-align:middle;
}

2.3 方法三

利用Css3的transform,可以轻松的在未知元素的宽高的情况下实现元素的垂直居中。代码如下:

#container {
    position:relative;
}
 
#div {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}

2.4 方法四

使用flex布局,无需绝对定位等改变布局的操作,可以轻松实现元素的水平垂直居中。代码如下:

#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