1.absolute定位+自适应边距
html
<div class="father">
<div class="son"></div>
</div>
css
.father{
position: relative; /* 设置父元素定位 */
width: 200px;
height: 200px;
border: 2px solid black;
}
.son{
width: 100px;
height: 100px;
background-color: lawngreen;
position: absolute; /* 设置子元素绝对定位 */
top: 0;
left: 0;
right: 0;
bottom: 0; /* 设置子元素4个边距为0 */
margin: auto; /* 设置子元素外边距自适应 */
}
特点
兼容IE8以及以上浏览器
元素宽高不需固定,可以随内容适应
2.absolute定位+负外边距
.father{
position: relative;
width: 200px;
height: 200px;
border: 2px solid black;
}
.son{
width: 100px;
height: 100px;
background-color: blueviolet;
position: absolute; /* 设置子元素绝对定位 */
top: 50%;
left: 50%; /* 设置子元素上和左边距为50%*/
margin-left: -50px;
margin-top: -50px; /* 子元素左和上外边距减去自身宽高的一半*/
}
特点
兼容性较好,能够兼容到IE6
元素的宽高需要固定
比较经典的垂直居中实现方式
3.absolute定位+css3平移
.father{
position: relative;
width: 200px;
height: 200px;
border: 2px solid black;
}
.son{
width: 100px;
height: 100px;
background-color: mediumaquamarine;
position: absolute; /* 设置子元素绝对定位 */
transform: translate(50%,50%); /* 设置子元素相对于父元素向下、向右平移50%*/
}
特点
由于使用了CSS3中的transform属性,需要IE9+浏览器
元素宽高不需固定,可以随内容适应
4.使用flex布局
.father{
width: 200px;
height: 200px;
border: 2px solid black;
display: flex; /* 设置父元素flex布局 */
justify-content: center; /* 设置父元素内子元素在主轴方向上居中*/
align-items: center; /* 设置父元素内子元素在交叉轴方向上居中*/
}
.son{
width: 100px;
height: 100px;
background-color: navy;
}
特点
简单直接
兼容性较差,需要IE10+
父元素高度需要指定
元素的宽高可以随内容适应