实现居中的方案有很多,这里介绍下纯CSS使用absolute配合margin的方案。
1. div宽高固定
width: 400px;height: 200px;position: absolute;top: 50%;left: 50%;margin-top: -100px;margin-left: -200px;
margin-top为-(height / 2),margin-left为-(width / 2)。当然也可以不用margin,即top为calc(100% - height) / 2,left为calc(100% - width) / 2,但是建议可以不用calc()就不要用。
2. div宽高不固定
width: 50%;height: 50%;position: absolute;top: 0;right: 0;bottom: 0;left: 0;margin: auto;
注意,这适用于宽高需指定的情况,比如使用百分比或者用js动态修改,不然可能被当成100%处理。
原标题:CSS实现div水平垂直居中
关键词:CSS