当你和面试官吹逼,或者面试官和你吹逼的时候可以拿来一用
1、2、6、7用的较多
1.绝对定位
需要指定子元素高度,不然会占满容器
.container{
position:relative;
}
.element{
position:absolute;
top: 0; bottom: 0; left: 0; right: 0;
margin: auto;
height: 20px;
}
2.transform
可能会妨碍其他的动画
.container{
position: relative;
}
.element{
position: absolute;
top: 50%;
transform: translateY(-50%);
}
3.table与table-cell
一言难尽的东西。。。
.container{
display: table;
height: 100%;
}
.element{
display: table-cell;
text-align: center;
vertical-align: middle;
}
4.伪元素
利用容器的伪元素,修改容器的baseline为middle,很巧妙
.container::before {
content: '';
display: inline-block;
height: 100%;
vertical-align: middle;
margin-left: -1ch;
}
.element{
display: inline-block;
vertical-align: middle;
}
5.flex与margin
只对单个元素有效
.container{
display:flex;
}
.element{
margin:auto;
}
6&7 flex
.container{
display: flex;
justify-content: center;
align-items: center;
}
.container{
display: flex;
}
.element{
align-self: center;
margin: 0 auto;
}
8&9grid
.container{
display: grid;
align-items: center;
justify-content: center;
}
.container{
display: grid;
}
.element{
justify-self: center;
align-self: center
}
10.伪元素与grid
.container{
display: grid;
grid-template-columns: 1fr;
grid-template-rows: repeat(3, 1fr);
}
.container::before,
.container::after{
content:"";
}
11.grid row
.container{
display:grid;
grid-template-columns:1fr;
grid-template-rows: repeat(3, 1fr);
}
.element{
grid-row: 2 / span 1; /* or grid-row: 2/3 */
}
12.grid与margin
.container{
display:grid;
grid-template-columns:1fr;
grid-template-rows: repeat(3, 1fr);
}
.element{
grid-row: 2 / span 1; /* or grid-row: 2/3 */
}
13.padding与border-box
当容器与子元素的高度都知道的时候
.container{
height:200px;
box-sizing: border-box;
padding: 50px 0;
}
.element{
height: 100px;
}
14.height与line-height
.container{
height:200px;
line-height:200px
}
.element{
}