目标:设置html元素水平居中和垂直居中,介绍三种方法。
方法一:推荐,兼容性好,没有冲突
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title><style type="text/css">div.box {height: 400px;width:200x;/* 给元素设置定位 */position:absolute;left: 50%;top: 50%;/* 设置为自身宽度的负一般 */margin-left: -100px;/* 设置为自生高度的负一半 */margin-top: -200px;}</style></head><body><div class="box"></div></body></html>
2.第二种:兼容性不好只支持IE9以上浏览器
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title><style type="text/css">div.box{height: 400px;width: 200px;position: absolute;left: 50%;top: 50%;transform: translate(-50%,-50%);}</style></head><body><div class="box"></div></body></html>
3.第三种:兼容性好但是不支持IE7一下版本
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title><style type="text/css">div.box {height: 400px;width: 200px;position: absolute;left: 0;right: 0;top: 0;bottom: 0;margin: auto;}</style></head><body><div class="box"></div></body></html>