注意:如容器不设置宽高,需要设置html,body { width: 100%; height: 100%; margin: 0;}
方法一:四个方向绝对定位为0 + margin: auto;
.box {
background-color: aquamarine;
position: relative;
height: 500px;
}
.content {
background-color: #ffff00;
margin: auto;
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
height: 50%;
width: 50%;
}
<div class="box"><div class="content"></div></div>
注:
此方法需父、子元素声明高度!!宽度可选(块级元素默认100%)
可支持百分比%宽高。兼容IE8+
方法二:绝对定位 50% + 负外边距 数值为自身宽高一半
.box2 {
background-color: rgb(236, 255, 127);
position: relative;
height: 500px;
}
.content2 {
background-color: #00ff9d;
width: 50%;
height: 200px;
position: absolute;
top: 50%;
left: 50%;
margin-top: -100px;
margin-left: -25%;
}
<div class="box2"><div class="content2"></div></div>
注:
不支持百分比尺寸!!!子元素高度不支持百分比!!宽度可用?
兼容IE6-IE7
方法三:绝对定位 50% + transform: translate(-50%,-50%);
.box3 {
background-color: rgb(236, 255, 127);
position: relative;
height: 500px;
}
.content3 {
background-color: #00ff9d;
width: 50%;
height: 50%;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
<div class="box3"><div class="content3"></div></div>
注:
子元素宽高可支持百分比!!
与方法二原理类似,将负外边距换为transform: translate(-50%,-50%);
方法四:弹性盒----flex
.box4 {
background-color: rgb(0, 255, 127);
height: 600px;
display: flex;
justify-content: center;
align-items: center;
}
.content4 {
background-color: #e139e7;
width: 50%;
height: 50%;
}
<div class="box4"><div class="content4"></div></div>
注:
父元素设置:
display: flex;
justify-content: center;
align-items: center;
子元素设置宽高即可。
如有更多、更好的方法,欢迎各位大佬补充修改,提出建议!
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。