方法1: table + vertical-align
上下居中
#parent {
display: table;
}
#child {
display: table-cell;
vertical-align: middle;
}
方法2: 绝对定位 + 上下左右设为0
*上下左右居中,需要设置宽高*
#parent {
position: relative;
height: 200px;
}
#child {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
width: 50%;
height: 30%;
margin: auto;
}
方法3: 绝对定位 + 相对自身margin
上下左右居中,需要事先知道child宽高
#parent {
position: relative;
}
#child {
position: absolute;
top: 50%;
left: 50%;
height: 30%;
width: 50%;
margin: -15% 0 0 -25%;
}
方法4: css3 transform: translate(-50%)
上下左右居中
#parent {
position: relative;
height: 200px;
}
#child {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%);
}
方法5 flex
略,详见Flex布局
左右居中可用margin: 0 auto; 或视情况用text-align: center;
林秀栋的技术博客