2018-11-05 CSS+div => 水平居中、垂直居中、水平垂直居中

HTML代码


CSS代码

.father {
    width: 500px;
    height: 300px;
    background-color: lightskyblue;
}

.son {
    width: 100px;
    height: 100px;
    background-color: lightgreen;
}

初始效果

以下代码都是基于上面代码添加

A => 水平居中

效果预览
  1. flex方式
.father {
    display: flex;
    justify-content: center;
}
  1. 定位 + left方式(已知宽度可以用margin-left, 未知宽度用transform)
.father {
    position: relative; /*想知道为什么加这一句,去掉看son对谁居中就知道了*/
}
.son {
    position: absolute;
    left: 50%;
    margin-left: -50px; /* 已知宽度 */
    /*transform: translateX(-50%);/* 未知宽度,这里的50%是参考自身实际宽度 */
}
  1. margin auto方式
.son {
    margin: 0 auto;
}

B => 垂直居中

效果预览
  1. flex方式
.father {
    display: flex;
    align-items: center;
}
  1. 定位 + top方式(已知、未知宽度同理)
.father {
    position: relative;
}
.son {
    position: absolute;
    top: 50%;
    margin-top: -50px;
    /*transform: translateY(-50%);*/
}
  1. table-cell + vertical-align方式
.father {
    display: table-cell;
    vertical-align: middle;
}

C => 水平垂直居中

效果预览
  1. flex方式
.father {
    display: flex;
    justify-content: center;
    align-items: center;
}
  1. 定位 + top left方式(已知、未知宽度同理)
.father {
    position: relative;
}

.son {
    position: absolute;
    top: 50%;
    left: 50%;
    margin-top: -50px;
    margin-left: -50px;
/*transform: translate(-50%,-50%);*/
}
  1. table-cell + vertical-align + margin auto方式
.father {
    display: table-cell;
    vertical-align: middle;
}

.son {
    margin: auto;
}

吃完东西擦嘴,学完东西总结

如果不考虑兼容性,那就用flex吧,其次,定位的方式也常用,table-cell比较冷门,多一条后路
跟我念:flex、定位、table-cell ... flex、定位、table-cell

什么?不够,那继续看这个吧 >> 何居中一个元素(终结版)

你可能感兴趣的:(2018-11-05 CSS+div => 水平居中、垂直居中、水平垂直居中)