1. 水平和垂直都居中
效果图
相关代码
<div id="outer">
<div id="insider"></div>
</div>
html, body {
width: 100%;
height: 100%;
}
#outer{
width: 80%;
height: 60%;
background-color: burlywood;
position: relative;
}
#insider{
width: 60%;
height: 50%;
background-color: cornflowerblue;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
注意事项
1. 由于外层及内层的div的宽高都是百分比,所以这里要将html及body的宽高也定义出来
2. 内层div的position为absolute,而外层的position为relative。
3. 真正调节位置的是 top left 及 transform translate(-50%, -50%)
2. 水平居中
效果图
相关代码
html, body {
width: 100%;
height: 100%;
}
#outer{
width: 80%;
height: 60%;
background-color: burlywood;
position: relative;
}
#insider{
width: 60%;
height: 50%;
background-color: cornflowerblue;
position: absolute;
left: 50%;
transform: translateX(-50%);
}
3. 垂直居中
效果图
相关代码
html, body {
width: 100%;
height: 100%;
}
#outer{
width: 80%;
height: 60%;
background-color: burlywood;
position: relative;
}
#insider{
width: 60%;
height: 50%;
background-color: cornflowerblue;
position: absolute;
top: 50%;
transform: translateY(-50%);
}