css如何设置div居中显示?

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

使用CSS设置div水平居中

在CSS中,可以使用margin:0 auto设置div水平居中。其中,auto就是左右自适应两边距离一样。

margin属性用于设置一个元素所有外边距的宽度,或者设置各边上外边距的宽度。

块级元素的垂直相邻外边距会合并,而行内元素实际上不占上下外边距。行内元素的的左右外边距不会合并。同样地,浮动元素的外边距也不会合并。允许指定负的外边距值,不过使用时要小心。

属性值:

  • auto:浏览器计算外边距。

  • length:规定以具体单位计的外边距值,比如像素、厘米等。默认值是 0px。

  • %:规定基于父元素的宽度的百分比的外边距。

示例:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<style>
			.center {
				width: 300px;
				height: 200px;
				background-color: #009999;
			}
			
			.box {
				width: 100px;
				height: 100px;
				background-color: red;
				margin: 0 auto;
			}
		</style>
	</head>

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

</html>

效果图:

1.jpg-600

使用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 答疑