CSS保持浮层水平垂直居中

前言

子绝父相:子元素绝对定位,父元素相对定位。让子元素 以其父元素为标准来定位。
如果父元素没有相对定位的话,子元素就会相对body或浏览器定位产生不好的效果。
在平常使保持浮层水平垂直居中,是我们经常遇到的一个问题,因浏览器版本或者元素的宽度、高度不确定等问题,往往需要使用不同的方式来应对。

使用绝对定位和transform

如果不确定子元素的宽度高度下,可以使用此方法。不过transform (2D)IE只有9或以上支持。

1
<div class="parents">
2
    <div class="children"></div>
3
</div>
1
.parent {
2
    position: absolute;
3
    background-color: #eee;
4
    width: 100%;
5
    height: 100%;
6
}
7
.parent .children {
8
    background: black;
9
    width: 200px;
10
    height: 200px;
11
    position: absolute;
12
    top: 50%;
13
    left: 50%;
14
    transform: translate(-50%, -50%);
15
}

使用 FlexBox

1
.parent{
2
    display:flex;
3
    justify-content: center;
4
    align-items: center;
5
    background-color: #eee;
6
    width: 100%;
7
    height: 100%;
8
}
9
.parent .children{
10
    background:black;
11
    width: 200px;
12
    height: 200px;
13
}

利用绝对定位和margin负值来实现

当子元素的宽高固定,父元素内含有除居中元素外其它元素(空标签也行)或者父元素的高度不为0时

1
.parent {
2
    height: 400px;
3
    position: relative;
4
    background: white;
5
}
6
7
.children {
8
    width: 200px;
9
    height: 200px;
10
    margin: -100px 0 0 -100px;
11
    background: black;
12
    position: absolute;
13
    top: 50%;
14
    left: 50%;
15
}

利用绝对定位与 margin:auto

1
.parent{
2
    width: 100%;
3
    height: 600px;
4
    background: white;
5
    position: relative;
6
}
7
.children{
8
    width: 100px;
9
    height: 100px;
10
    background-color: black;
11
    position: absolute;
12
    top: 0;
13
    left: 0;
14
    bottom: 0;
15
    right: 0;
16
    margin: auto;
17
}

通过verticle-align:middle实现

1
.parent{
2
    width: 100%;
3
    height: 600px;
4
    background: white;
5
}
6
.children{
7
    width: 100px;
8
    height: 100px;
9
    background-color: black;
10
    display: inline-block;      // 必须蒋元素设置未 inline-block
11
    vertical-align: middle;
12
}

本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!