实现垂直水平居中有多种方法,今天在这里介绍我自己认为较为简单的三种方法。
方法一:使用position定位
代码如下:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<title>实现垂直水平居中方法1</title>
	</head>
	<style>
		html,body,div{
			margin:0;
			padding:0;
		}
		body{
		height:100%;
		width:100%;
		}
		#center{
			width:200px;
			height:200px;
			background:red;
			margin:0 auto;/*实现水平居中*/
			position:relative;/*设置相对定位,移动div*/
			top:50%;/*将图片移动到中间*/
			margin-top:-100px;/*关键设置,定位移动后,只是相当于将一个元素上边界中心点居中,而元素div是有
			宽高的,应减去元素的高度的一半,让元素实现中心点居中*/
		}
	</style>
	<body>
		<div id="center">垂直水平居中</div>
	</body>
</html>

效果图片如下:
实现垂直水平居中的三种方法

方法二:使用position和transform

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>实现水平垂直居中方法2</title>
	<style>
			html,body{
				margin:0;
				padding:0;
				height:100%;
				width:100%;
			}
			#center{
			height:200px;
			width:200px;
			background:green;
			margin:0 auto;/*实现水平居中*/
			position:relative;/*设置定位,偏移量,让元素实现上下居中*/
			top:50%;
			transform: translateY(-50%);/*使用平移使图片居中,思想与方法一一致*/
			}
		</style>
	</head>
	<body>
		<div id="center">垂直水平居中</div>
	</body>
</html>

效果图如下:
实现垂直水平居中的三种方法

方法三:使用弹性盒子

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>实现水平垂直居中方法3</title>
	<style>
			html,body{
				margin:0;
				padding:0;
				height:100%;
				width:100%;
			}
			body{
				display:flex;/*打开弹性盒子(在父元素中使用)*/
				justify-content:center;/*控制水平居中*/
				align-items:center;/*控制垂直居中*/
			}
			#center{
			height:200px;
			width:200px;
			background:orange;
			}
		</style>
	</head>
	<body>
		<div id="center">垂直水平居中</div>
	</body>
</html>

实现的效果如下:
实现垂直水平居中的三种方法

今天就介绍到这里,如果喜欢,欢迎点赞关注,欢迎各位大佬探讨,今后会不定时更新一些好用的方法与大家分享。

相关文章:

  • 2021-08-17
  • 2021-11-26
  • 2021-10-28
  • 2021-12-04
  • 2021-11-21
  • 2021-11-27
  • 2021-08-03
  • 2021-12-04
猜你喜欢
  • 2022-12-23
  • 2021-08-31
  • 2021-12-04
  • 2021-04-16
  • 2022-02-01
  • 2021-12-22
  • 2022-12-23
相关资源
相似解决方案