居中

一、文本居中

水平居中:text-align: center;

单行文本垂直居中
line-height: xxxpx;(父盒子行高 = 父盒子高度)

多行文本垂直居中

  • 方法1,利用弹性布局flex+align-items
.box {
    display: flex;
    align-items: center;

    width: 500px;
    height: 500px;
    background-color: yellow;   
}

方法2,父line-height+子行内块+子line-height自定义设置

先对父元素设置高度和行高(相等),将子元素设置为行内块元素,模拟成单行文本,再对子元素设置vertical-align: middle;使其基线对齐,这时还未实现垂直居中,为子元素自定义line-height属性的值,覆盖继承自父元素的行高,即可实现垂直居中。
.box {
    width: 500px;
    height: 500px;
    line-height: 500px;
    background-color: yellow;
}
span {
    display: inline-block;
    vertical-align: middle;
    line-height: 18px;
}

方法3,子元素设为行内块元素+利用相对定位进行平移(translateY)

.text {
    width: 500px;
    height: 500px;
    background-color: yellow;
}
span {
    display: inline-block;
    position: relative;
    top: 50%;
    transform: translateY(-50%);
}

方法4,利用表格元素table+vertical-align实现

.text {
    display: table;
    width: 500px;
    height: 500px;
    background-color: yellow;
}
span {
    display: table-cell;
    vertical-align: middle;
}
二、图片居中
  • 方法1:
    水平居中,给父元素设 text-align: center;
    垂直居中,给父元素设 line-height: xxxpx 的同时给图片设 vertical-align: middle;

  • 方法2:
    给父元素设 background: url(./upload/floor-1-1.png) no-repeat center center;

三、图片和文本对齐



    
    
    
    
    Document
    


    
  • 手机号码格式不正确,请重新输入
预览.jpg

你可能感兴趣的:(居中)