关于div元素居中

先看图

代码如下:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<style>
			span{
				font-size: 17px;
			}
			.main{
				display: flex;
				flex-wrap: wrap;
			}
			.demo {
				width: 300px;
				height: 300px;
				border: 1px solid purple;
				display: flex;
				justify-content: center;
				/*水平居中*/
				align-items: center;
				/*垂直居中*/
			}

			.inner {
				width: 100px;
				height: 100px;
				font-size: 26px;
				border: 1px solid red;
				background-color: antiquewhite;
			}
			.demo2 {
				width: 300px;
				height: 300px;
				border: 1px solid red;
				position: relative;
			}
			.inner2 { 
				width: 100px;
				height:100px;
				border: 1px solid black;
				background-color: greenyellow;
		
				position: absolute;
				margin: 0 auto;
				left:0;
				right:0;
				/* top:0; */
				/* bottom:0 */
			}
			.demo3 {
				width: 300px;
				height: 300px;
				border: 1px solid red;				
				position: relative;
			}
			.inner3 { 
				width: 100px;
				height:100px;
				border: 1px solid black;
				background-color: greenyellow;
				
				position: absolute;
				margin-top: auto;
				margin-bottom: auto;
				top:0;
				bottom:0;
			}
			.demo4 {
				width: 300px;
				height: 300px;
				border: 1px solid red;				
				position: relative;
			}
			.inner4 { 
				width: 100px;
				height:100px;
				border: 1px solid black;
				background-color: greenyellow;
				
				position: absolute;
				left: 0;
				right: 0;
				top: 0;
				bottom: 0;
				margin: auto;
			}
		</style>
	</head>
	<body>
		<div class="main">
			<div class="demo">
				<div class="inner">
					<span>demo:</br>flex垂直居中</p>
				</div>
			</div>
			<div class="demo2">
				<div class="inner2">
					<span>demo2:<br />
					绝对定位水平居中</span>
				</div>
			</div>
			<div class="demo3">
				<div class="inner3">				
				<span>demo3:<br />绝对定位垂直居中</span>
				</div>
			</div>
			<div class="demo4">
				<div class="inner4">	
					<span>demo4:<br />绝对定位水平垂直居中</span>
				</div>
			</div>
		</div>
	</body>
</html>

可参考文章

1.水平垂直居中——position与margin的结合使用

https://blog.csdn.net/fxss5201/article/details/73755275

2.30分钟彻底弄懂flex布局

猜你喜欢

转载自blog.csdn.net/aq9527/article/details/88776059