用于积累css中的实用代码段。按照实现的功能进行划分,不区分先后。

水平垂直居中

下面为公共代码:

<div class="box">
    <div class="small">small</div>
</div>
1
2
3
.box {
    width: 300px;
    height: 300px;
    background: #ddd;
}
.small {
    background: red;
}
1
2
3
4
5
6
7
8

水平垂直居中-->>absolute + margin实现

absolute + margin 第1种

.box {
    position: relative;
}
.small {
    position: absolute;
    top: 50%;
    left: 50%;
    margin: -50px 0 0 -50px;
    width: 100px;
    height: 100px;
}
1
2
3
4
5
6
7
8
9
10
11

Open in CodePen

absolute + margin 第2种

.box {
    position: relative;
}
.small {
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    margin: auto;
    width: 100px;
    height: 100px;
}
1
2
3
4
5
6
7
8
9
10
11
12
13

Open in CodePen

水平垂直居中-->>absolute + calc 实现

.box {
    position: relative;
}
.small {
    position: absolute;
    top: calc(50% - 50px);
    left: calc(50% - 50px);
    width: 100px;
    height: 100px;
}
1
2
3
4
5
6
7
8
9
10

Open in CodePen

水平垂直居中-->>absolute + transform 实现

.box {
    position: relative;
}
.small {
    position: absolute;
    top: 50%;
    left: 50%;
    /* transform: translate(-50%,-50%); */
    transform: translate3d(-50%,-50%,0);
    width: 100px;
    height: 100px;
}
1
2
3
4
5
6
7
8
9
10
11
12

Open in CodePen

水平垂直居中-->>转行内元素

.box {
    line-height: 300px;
    text-align: center;
    font-size: 0px;
}
.small {
    padding: 6px 10px;
    font-size: 16px;
    display: inline-block;
    vertical-align: middle;
    line-height: 16px;
}
1
2
3
4
5
6
7
8
9
10
11
12

Open in CodePen

水平垂直居中-->>table-cell

.box {
    display: table-cell;
    text-align: center;
    vertical-align: middle;
}
.small {
    padding: 6px 10px;
    display: inline-block;
}
1
2
3
4
5
6
7
8
9

Open in CodePen

水平垂直居中-->>flex

flex 第1种

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

Open in CodePen

flex 第2种

.box {
    display: flex;
    justify-content: center;
}
.small {
    align-self: center;
}
1
2
3
4
5
6
7

Open in CodePen

水平垂直居中-->>grid

grid 第1种

.box {
    display: grid;
    justify-items: center;
    align-items: center;
}
1
2
3
4
5

Open in CodePen

grid 第2种

.box {
    display: grid;
}
.small {
    justify-self: center;
    align-self: center;
}
1
2
3
4
5
6
7

Open in CodePen

grid 第3种

.box {
    display: grid;
    justify-items: center;
}
.small {
    align-self: center;
}
1
2
3
4
5
6
7

Open in CodePen

grid 第4种

.box {
    display: grid;
    align-items: center;
}
.small {
    justify-self: center;
}
1
2
3
4
5
6
7

Open in CodePen

Firefox ::-moz-focus-inner

对于点击某些元素后出现的边框,去除的办法是:

button:focus {
    outline: none;
}
1
2
3

但是在 Firefox 下,对于类型为button的元素,即使设置outline,也还是会出现虚线。这个时候就需要用 Firefox 的私有伪元素::-moz-focus-inner

button::-moz-focus-inner {
    border: 0;
}
1
2
3
上次更新: 2019-7-30 16:57:46