前端面试题HTML+CSS基础篇——盒子垂直水平居中

141 阅读1分钟

盒子垂直水平居中

  1. margin:auto

父元素宽高固定,子绝父相,父元素相对定位,子元素绝对定位

.father {

height: 200px;  
width: 200px;
position: relative;

}

.son{

position: absolute;
width: 80px;
height: 80px;
top: 0;
left: 0;
bottom: 0;
right: 0;
margin: auto;

}

  1. 子绝父相,已知宽高的情况下

.father{

height: 200px;
width: 200px;
position: relative;

}

.son{

position: absolute;
width: 80px;
height: 80px;
left: 50%;
top: 50%;
margin-left: -40px;
margin-top: -40px;

}

  1. css3属性transform

.father{

height: 200px;
width: 200px;
position: relative;

}

.son{

position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%,-50%);

}

这种方式,相对于第二种来说,优势在于不需要已知子元素的宽高

  1. flex布局

.father{

height: 200px;
width: 200px;
display: flex;
justify-content: center;
align-items: center;

}

不需要知道宽高,推荐使用这种方式,十分简便,所有浏览器都兼容

  1. table布局

.father{

height: 200px;
width: 200px;
display: table;

}

.son{

display: table-cell;
text-align: center;
line-height: 200px;

}

这几种水平垂直居中的方法在面试过程中都有考察,是前端一个最最最基本的内容!