css 水平 垂直居中

没有特别的幸运,那么就特别的努力!!!

水平居中:适用于一些样式布局,特别是需求图片,等宽不等高或等高不等宽有的宽高不确定…
但最终效果——要垂直居中显示,解决方案如下:

水平居中

1.行内元素

.box{
    text-align: center;
}

2.块级元素

.info{
    margin: 0 auto;
}

3.flex布局

.parent {
    display: flex;
    justify-content: center;
}

4.绝对定位定宽

.box {
    position: absolute;
    width: 宽度;
    left: 50%;
    margin-left: -0.5*宽度
}

5.绝对定位不定宽

.box{
    position: absolute;
    left: 50%;
    transform: translate(-50%, 0);
}

6.left/right: 0

.son {
    position: absolute;
    width: 宽度;
    left: 0;
    right: 0;
    margin: 0 auto;
}

垂直居中

1.行内元素

.parent {
    height: 高度;
}
.son {
    line-height: 高度;
}

2.块级元素

.parent {
  display: table;
}
.son {
  display: table-cell;
  vertical-align: middle;
}

3.flex布局

.info {
    display: flex;
    align-items: center;
}

4.绝对定位定宽

.box {
    position: absolute;
    top: 50%;
    height: 高度;
    margin-top: -0.5高度;
}

5.绝对定位不定宽

.box{
    position: absolute;
    top: 50%;
    transform: translate( 0, -50%);
}

6.left/right: 0

.hammer {
    position: absolute;
    height: 高度;
    top: 0;
    bottom: 0;
    margin: auto 0;
}
拿着 不谢 请叫我“锤” !!!

希望以上分享能帮到大家,祝大家在开发旅途中愉快!!!

猜你喜欢

转载自blog.csdn.net/hammer1010/article/details/103618459