本节来总结一下块级元素垂直居中布局的方式,以下例子如果未特别说明统一使用这样的html结构:
<div class="container">
<div class="content"></div>
</div>
一、绝对定位:
绝对定位可以把元素大概定位在垂直居中的位置,然后需要通过margin、transform和calc的方式来调整居中元素一半的距离。
1.margin+像素数来调整间距:
.container {
background: #777777;
height: 400px;
position: relative;
}
.container .content {
width: 100px;
height: 100px;
position: absolute;
top: 50%;
margin-top: -50px;
left: 50%;
margin-left: -50px;
background: #ee5f28;
}
优点:兼容性好。 缺点:需要知道居中元素的高度。
2.transform变形来调整元素的偏离:
.container {
background: #777777;
height: 400px;
position: relative;
}
.container .content {
width: 100px;
height: 100px;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background: #ee5f28;
}
在transform变形属性中,我们常用的有translate转换,参数可以为像素数和百分数,表示按一定方向转换当前元素百分比的坐标,所以可以不考虑居中元素的大小。其他常用的属性还有scale缩放,rotate旋转。scale的系数为倍数,即1不缩放,2表示在某个方向上缩放两倍。rotate系数单位为deg表示角度,顺时针为正。并且同时起作用的还有transform-origin这个参数,表示旋转的基准点的坐标,值可以为百分比、像素数、中心,上下左右位置。需要注意的是,在进行变形时,这三个参数的顺序不同,形变的最终效果可能也不同。
3.通过calc来计算绝对定位的位置:
.container {
background: #777777;
height: 400px;
position: relative;
}
.container .content {
width: 100px;
height: 100px;
position: absolute;
top: calc(50% - 50px);
left: calc(50% - 50px);
background: #ee5f28;
}
calc一般用来计算百分比和数量单位的表达式,也是需要知道居中元素的大小。
二、flex布局:
1.控制父级容器元素,使单一子级块元素垂直居中:
.container {
background: #777777;
height: 400px;
display: flex;
justify-content: center;
align-items: center;
}
.container .content {
width: 100px;
height: 100px;
background: #ee5f28;
}
flex在父元素中通过justify-content:center; 定义了子元素项目在主轴上的对齐方式为居中,align-items:center; 定义子元素项目在交叉轴上的中点对齐,详细资料点击"flex"进行了解。
2.通过子元素的margin进行调整:
.container {
background: #777777;
height: 400px;
display: flex;
}
.container .content {
width: 100px;
height: 100px;
background: #ee5f28;
margin: auto;
}
flex默认会把子级项目排列到左上角,但是如果子级项目加上了margin: auto; 就可以让子元素正常居中了。
更多精彩文章请关注:
对于初入职场的你想知道行业内技术水平如何么?遇到的技术点有没有由于长期没有再接触容易忘记呢?『全栈编程』刷题小程序就是专门来解决上述两个问题的,其中题目全部出自一线大厂小哥的工作实践,每月刷题最多的同学可以任选100元以内图书一本哦~