CSS中关于居中的几种设置方法

1.最普通型(水平居中)

  div{200px;margin: 0 auto;}

2.运用绝对定位来居中

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<title></title>
		<style type="text/css">
			.con{
				position: absolute;
				 300px;
				height: 200px;
				left: 0;
				right: 0;
				top: 0;
				bottom: 0;
				background-color: red;
				margin: auto;
			}
		</style>
	</head>
	<body>
		<div class="con"></div>
	</body>
</html>

  3.运用left和top的百分比来设定

  

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<title></title>
		<style type="text/css">
			.con{
				position: absolute;
				 300px;
				height: 200px;
				left: 50%;
				top: 50%;
				margin-left: -150px;
				margin-top: -100px;
				background-color: red;
			}
		</style>
	</head>
	<body>
		<div class="con"></div>
	</body>
</html>

 4.transform()

  

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<title></title>
		<style type="text/css">
			.con{
				position: absolute;
				 300px;
				height: 200px;
				left: 50%;
				top: 50%;
				transform: translate(-50%,-50%);
				background-color: red;
			}
		</style>
	</head>
	<body>
		<div class="con"></div>
	</body>
</html>

  

原文地址:https://www.cnblogs.com/lishengjun/p/6637016.html