二维码

基本操作

垂直置中

(1)方法一

原理:子元素的 top, right, bottom, left, margin, and padding属性,针对的是父元素的维度;transform针对的子元素本身的维度。

父元素、子元素需有明确高度,不能是auto。

1
2
3
4
5
6
7
8
9

.children{
background: #ffdb4c;
height: 300px;
position: relative;
top: 50%;
transform: translateY(-50%);
}

(2)方法二

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

.parent { position: relative; }

.child {
position: absolute;

left: 50%;
top: 50%;

-webkit-transform: translate(-50%, -50%);
-moz-transform: translate(-50%, -50%);
-ms-transform: translate(-50%, -50%);
-o-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
}

(3)方法三

1
2
3
4
5
6
.parent { display: table; }

.child {
display: table-cell;
vertical-align: middle;
}

(5)行内置中

1
2
3
4
5
6
.parent { line-height: 500px; }

.child {
display: inline-block;
vertical-align: middle;
}

(6)方法四(只对图片有效)

1
2
3
4
5
6
7
8
9
10
11
.thumb {
background-image: url(my-img.jpg);
background-position: center;
/* is this supported by IE8? I don't know */
background-size: cover;

height: 0;
overflow: hidden;
padding-bottom: 50%;
width: 50%;
}

(7)方法五

1
2
3
.children {
margin-top: calc(50% - 12.5%);
}

(8)方法六

1
2
3
4
5
.container {
display: flex;
justify-content: center;
align-items: center;
}

(9)参考链接

清理浮动

1
2
3
4
5
6
7
8
9
10
11
12
13
14

.clearfix:after{
visibility:hidden;
display:block;
font-size:0;
content:" ";
clear:both;
height:0;
}

.clearfix{
zoom:1; /* for IE6 IE7 */
}


本教程来自“网道项目”(wangdoc.com),采用知识共享 署名-相同方式共享 3.0协议