在网页中有很多需要居中的情况,它包含的知识点也是比较丰富,那么作为一位合格的前端er你都会吗?
元素定宽高
下面列举一下在居中元素定宽高的情况下我们要怎么做
计算法
- absolute + margin
/* 节点情况
<body>
<div class="father">
<div class='child'></div>
</div>
</body>
<style>
.father{
position: relative;
border: 10px solid red;
width: 300px;
height: 300 px;
}
.child{
position: absolute;
top: 50%;
left: 50%;
width: 100px;
height: 100px;
margin-left: -50px;
margin-top: -50px;
background-color: aqua;
}
</style>
注意点
- 使用absolute偏移后,还要根据自身的大小做相对应的修正
- 使用absoulte 父节点不能是static定位
2.absolute + calc
<style>
.father{
position: relative;
border: 10px solid red;
width: 300px;
height: 300px;
}
.child{
position: absolute;
top: calc(50% - 50px);
left: calc(50% - 50px);
width: 100px;
height: 100px;
background-color: aqua;
}
</style>
原理和第一种是差不多的。
margin auto
- absolute + margin: auto
<style>
.father{
position: relative;
border: 10px solid red;
width: 300px;
height: 300px;
}
.child{
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
width: 100px;
height: 100px;
background-color: aqua;
}
</style>
- 设置top:0,left:0,right:0,bottom:0本质目的,是让子盒子四边与父容器间距为0,而子盒子没有明确宽高,自然被拉伸到完全填满父容器了。
三种方法的结果如下
居中元素不定宽高
先给出节点信息
<body>
<div class="father">
<div class='child'>hello css</div>
</div>
</body>
- absoulte + transform
<style>
.father{
position: relative;
border: 10px solid red;
width: 300px;
height: 300px;
}
.child{
position:absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
background-color: aqua;
}
</style>
- translate 可以设置百分比这是基于自身的宽和高算出来的
- 设置成行内元素
<style>
.father{
/* position: relative; */
border: 10px solid red;
line-height: 300px;
width: 300px;
text-align: center;
}
.child{
font-size: 20px;
display: inline-block;
vertical-align: middle;
line-height: initial;
}
</style>
- 通过text-align 实现水平居中
- 通过vertical 实现垂直居中
- 使用css-table
<style>
.father{
display: table-cell;
border: 10px solid red;
height: 300px;
width: 300px;
vertical-align: middle;
text-align: center;
}
.child{
font-size: 16px;
display: inline-block;
}
</style>
或者
<style>
.father{
display: table;
border: 10px solid red;
height: 300px;
width: 300px;
text-align: center;
}
.child{
line-height: 1;
display: table-cell;
vertical-align: middle;
}
</style>
- display: table-cell 相当于是td标签
总体效果如下
flex布局
很简单flex布局在当今非常常用,建议认真巩固一下 这里推荐一下阮一峰老师的博客
<style>
.father{
display: flex;
border: 10px solid red;
height: 300px;
width: 300px;
justify-content: center;
align-items: center
}
</style>
gird布局
这种布局比较奇妙大家可以了解学习一下,但是兼容性不太好
<style>
.father{
display: grid;
border: 10px solid red;
height: 300px;
width: 300px;
}
.child{
justify-self: center;
align-self: center
}
</style>
总结一下
- 子元素宽高确定的情况下 有兼容性要求的可以采用absolute + margin的方法
- 兼容性要求,不定宽高用table布局
- 一般推荐使用flex布局