css样式设置元素居中的最简便方式 左右居中或垂直居中

左右居中

.class {
    width: 960px;
    margin: 0 auto;
}

垂直居中方式

父元素需要设置position为非static定位,如果需要左右也居中,加上left: 0;right: 0;即可。

.vMiddle {
    width: 100px;
    height: 100px;
    position: absolute;
    top: 0;
    bottom: 0;
    margin: auto;
}

样例代码

<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<style type="text/css">
			.middle {
				position: absolute;
				height: 100px;
				width: 100px;
				top: 0;
				bottom: 0;
				background-color: black;
				margin: auto;
			}
		</style>
	</head>
	<body>
		<div style="position:relative;width:200px;height:600px;background-color: aliceblue;">
			<div class="middle">
			</div>
		</div>
	</body>
</html>

相关推荐