css怎么使div居中显示?

在开发过程中,很多需求需要我们居中一个div,那么如何使div居中显示?下面本篇文章就来给大家介绍一下使用CSS设置div居中显示的方法,希望对大家有所帮助。

margin:0 auto实现div水平居中

HTML代码:

<div class="center">
       <div class="box"></div>
</div>

css代码:

.center{
width: 300px;
height: 200px;
background-color: #009999;
}
.box{
width: 100px;
height: 100px;
background-color: red;
margin:0 auto;
}

效果图:

1.jpg-600

CSS div垂直居中

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

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

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>css 垂直居中</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">css 垂直居中</div>
		</div>
	</body>
</html>

效果图:

3.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>

效果图:

4.jpg-600

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

3. 使用flex布局

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

效果图:

7.jpg-600

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

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