学习小程序,掌握一些前端常用的方法和逻辑很重要,平常注意总结,在需要的时候才能信手拈来。居中对齐,在页面布局中太过常见,所以能够有效的实现水平居中和垂直居中的效果尤为重要,能够实现不是目的,我们追求的是效率,一旦遇到类似的问题,能够立马找到对应的解决办法。下面我将会总结我们常用的几种居中对齐方法,与大家一起讨论。
.parent{
width: -moz-fit-content;
width: -webkit-fit-content;
width:fit-content;
margin:0 auto;
}
.parent{
display: flex;
justify-content: center;
}
.child{
position:absolute;
left:50%;
transform:translate(-50%,0);
}
.child{
position:absolute;
width:500px;
left:50%;
margin-left:-50%;
}
.child{
position:absolute;
width:100px;
left:0;
right:0;
margin:0 auto;
}
.parent {
height:300px;
line-height:300px;
}
.parent::after, .son{
display:inline-block;
vertical-align:middle;
}
.parent::after{
content:'';
height:100%;
}
.parent {
display:table;
}
.child {
display:table-cell;
vertical-align:middle;
}
.parent {
display: flex;
align-items: center;
}
.parent {
position:relative
}
.child{
position:absolute;
top:50%;
-webkit-transform: translate(-50%,-50%);
-ms-transform: translate(-50%,-50%);
transform: translate(-50%,-50%);
}
.parent {
position:relative
}
.child{
position:absolute;
height:100px;
top:0;
bottom:0;
margin:auto 0;
}
居中对齐的方法,当然不只以上几种,这里我只列举了几种常见或者使用起来比较简单的方法。我们在使用这些方法的时候,注意问题的场景,对症下药才能药到病除。如果你采用这些方法仍然达不到理想的效果,使用绝对的布局也还不错。所谓绝对的布局,其实就是,父级元素和子级元素长宽写死,使用margin,padding的尺寸等于它们的差就可以了。
补充:
按钮文字水平垂直居中怎么做,下面来个实操。
<button class="test"><text>我来了text>button>
.test {
background-color:red;
width:200rpx;
height:100rpx;
}
2. 默认是块级标签,居中对齐。但我们想要的布局肯定不会这么直白。我们加个display:inline-block看看。
.test {
display: inline-block;
background-color:red;
width:200rpx;
height:100rpx;
}
.test {
display: inline-block;
background-color:red;
width:100rpx;
height:60rpx;
}
咦?不正常,字体没有缩小,改下font-size试试
.test {
display: inline-block;
background-color:red;
width:100rpx;
height:60rpx;
font-size: 20rpx;
}
怎么回事?看到这是不是懵了,我也是!加个text-align看一看。
.test {
display: inline-block;
background-color:red;
width:100rpx;
height:60rpx;
font-size: 25rpx;
text-align: center;
}
.test {
display: inline-block;
background-color:red;
width:100rpx;
height:60rpx;
font-size: 25rpx;
text-align: center;
line-height: 60rpx;
}
.test {
display: inline-block;
background-color:red;
width:100rpx;
height:60rpx;
font-size: 25rpx;
padding: 0;
}
卧槽!可以了啊,怎么回事。。。。
总结:从上面,我们可以知道,button默认居中对齐,但文字长度超过阈值,居中效果就会失效。这时,我们可以重新设置padding值来达到目的。
参考:
https://www.w3cschool.cn/cssref/
https://juejin.im/post/6844903474879004680