已知宽高设置盒子水平垂直居中的方法:
1.position+margin方法:父相子绝,子给margin:auto;left0;right:0;top:0;bottom:0;缺点:兼容性:主流浏览器均支持,IE6不支持
2.diaplay:table-cell 兼容性:由于display:table-cell的原因,IE67不兼容
<!-- html -->
<div class="wrap">
<div class="center"></div>
</div>
/*css*/
.wrap{ width: 200px; height: 200px; background: yellow; display: table-cell; vertical-align: middle; text-align: center;}
.center{ display: inline-block; vertical-align: middle; width: 100px; height: 100px; background: green;}
3.纯定位实现postion 兼容性:适用于所有浏览器
<!-- html --><div class="wrap">
<div class="center"></div></div>
/* css */.wrap { background: yellow; width: 200px; height: 200px; position: relative;}
/**方法一**/.center { background: green; position: absolute; width: 100px; height: 100px; left: 50px; top: 50px;}
/**方法二**/.center { background: green; position: absolute; width: 100px; height: 100px; left: 50%; top: 50%; margin-left:-50px; margin-top:-50px;}
实现一个未知宽高的盒子水平居中的方法:
1.弹性盒:display:flex;just-content:center;align-item:center/align-content:center,搭配flex-wrap:wrap
2.弹性盒:display:flex;just-content:center;子元素加align-self:center
3.父盒子给display:flex; 子元素:margin:auto;(实现垂直水平居中)
4.定位属性postion配合位移(transform)属性:
父元素设置:position:relative,
- 子元素设置:position:absolute; top:50%; left:50%; transform:translate(-50%,-50%)