css怎么让div垂直居中?

在我们开发前端页面的时候,为了让页面效果美观,会出现需要垂直居中效果的地方。下面本篇文章就来给大家介绍一下使用CSS让div垂直居中的方法,希望对大家有所帮助。

1、使用绝对定位和负外边距对块级元素进行垂直居中 (已知元素的高度)

如果我们知道元素的高度,可以这样来实现垂直居中:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>css div垂直居中</title>
		<style>
			.box{
				width: 300px;
			    height: 300px;
			    background: #ddd;
			    position: relative;
			}
			.child{
				width: 150px;
			    height: 100px;
			    background: orange;
			    position: absolute;
			    top: 50%;
			    margin: -50px 0 0 0;
			    line-height: 100px;
			}
		</style>
	</head>
	<body>
		<div class="box">
		    <div class="child"></div>
		</div>
	</body>
</html>

效果图:

1.jpg-600

这个方法兼容性不错,但是有一个小缺点:必须提前知道被居中块级元素的尺寸,否则无法准确实现垂直居中。

2、使用绝对定位和transform(未知元素高度)

如果我们不知道元素的高度,那么就需要先将元素定位到容器的中心位置,然后使用 transform 的 translate 属性,将元素的中心和父容器的中心重合,从而实现垂直居中:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>css 垂直居中</title>
		<style>
			.box{
				width: 300px;
			    height: 300px;
			    background: #ddd;
			    position: relative;
			}
			.child{
				background: #93BC49;
			    position: absolute;
			    top: 50%;
			    transform: translate(0, -50%);
			}
		</style>
	</head>
	<body>
		<div class="box">
		    <div class="child">css 垂直居中,css 垂直居中,css 垂直居中,css 垂直居中,css 垂直居中</div>
		</div>
	</body>
</html>

效果图:

2.jpg-600

这种方法有一个非常明显的好处就是不必提前知道被居中元素的尺寸了,因为transform中translate偏移的百分比就是相对于元素自身的尺寸而言的。

3、使用flex布局

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>css div垂直居中</title>
		<style>
			.box{
				width: 300px;
			    height: 300px;
			    background: #ddd;
			    display: flex;
			    flex-direction: column;
			    justify-content: center;
			}
			.child{
				width: 200px;
			    height: 100px;
			    background: #08BC67;
			    line-height: 100px;
			}
		</style>
	</head>
	<body>
		<div class="box">
		    <div class="child"></div>
		</div>
	</body>
</html>

效果图:

3.jpg-600

更多前端开发知识,请查阅 HTML中文网 !!

以上就是css怎么让div垂直居中?的详细内容,更多请关注0133技术站其它相关文章!

赞(0) 打赏
未经允许不得转载:0133技术站首页 » CSS3 答疑