.parent{
height:200px;
width:200px;
border:1px solid #000;
}
.son{
width:100px;
background: red;
}
第一种:这里用的是css3的display:flex属性。
display: flex; //flex弹性布局
justify-content:center; //元素在主轴上(页面)排列顺序
align-items:center; //元素在主轴(页面)当前行的横轴(纵轴)方向上的对齐方式
.one{
display: flex;
align-items:center;
justify-content:center;
}
第二种:用 display: table-cell实现 。
display: table-cell; //元素以表格单元格的形式呈现
vertical-align: middle; //把元素放置在父元素的中部。
text-align: center; //水平居中
.two{
display: table-cell;
vertical-align: middle;
text-align: center;
}
.two .son{
display: inline-block;
}
第三种:用定位和css3的transform属性来实现。
position: relative; //相对定位
position: absolute; //绝对定位
transform: translate(x,y); //2D转换
.three{
position: relative;
}
.three .son{
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
效果:
小小前端,希望大家多提提意见,共同成长。