实现div内容水平居中
实现方案一:margin:0 auto;
div{
height:100px;
width:100px;
background:red;
margin:0 auto;
}
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>div水平居中</title>
</head>
<body>
<div></div>
</body>
</html>
实现div水平居中方案二:position:absolute;绝对定位
div{height:100px;width:100px;background:red;position:absolute;
left:50%;
right:50%;
margin: auto;
}
实现div水平垂直居中
实现方案一:position:fixed;固定定位
div{height:100px;width:100px;background:red;position:fixed;left:0;top:0;bottom:0;right:0;margin:auto;
}
实现方案二:position:absolute;绝对定位
div{height:100px;width:100px;background:red;position:absolute;left:0;top:0;bottom:0;right:0;margin:auto;
}
实现方案二:css3+position;
div{height:100px;width:100px;background:red;position:absolute;left:50%;top:50%;transform:translate(-50%,-50%);
}
transform为css3的新增属性,因此需要加上前缀,兼容手机和其他的浏览器。如
-ms-transform:translate(-50%,-50%); /* ie 9 */-moz-transform:translate(-50%,-50%); /* firefox */-webkit-transform:translate(-50%,-50%);/* safari and chrome */-o-transform:translate(-50%,-50%); /* opera */
以上就是css+div水平居中的实例代码的详细内容。
