使用浏览器线上的编辑器非常方便,比如JSRUN,可以参考这篇经验了解。
transform不兼容ie8或以下的浏览器,ie8或以下的浏览器现在只有不到1%的比例了,兼容性还是比较好的。
编写最简单的2个div嵌套
跟居中无关的的css代码分离出来.outer { width: 500px; height: 300px; background-color: green; position: relative;}.inner { width: 200px; height: 100px; background-color: wheat; position: absolute;}
只需要3行代码就能实现.center { left: 50%; top: 50%; transform: translate(-50%, -50%);}
上下.center { left: 50%; transform: translateX(-50%);}.center { left: 50%; transform: translateX(-50%);}
例如div结构如下
css如下.left { width: 400px; height: 200px; background-color: wheat;}.right { width: 100px; height: 200px; left: 0; top: 0; background-color: yellow; position: absolute; margin:8px}.inner{ width: 100px; height: 100px; background-color: green;}
使用transform能实现带像素偏移的居中.center { position:relative; margin-left: 50px; left: 50%; top: 50%; transform: translate(-50%, -50%);}
这个比较简单,把top或left的50%改成其它数值就行。例如向上偏移容器10%高度的代码是.center { left: 50%; top: 40%; transform: translate(-50%, -50%);}