css实现垂直居中

要想实现水平居中很简单,只需要margin: 0 auto;就可以了,但如果要实现垂直居中,就稍微麻烦一些了。
下面记录一些垂直居中的方法:

对于文本

对于<p>段落来说,要想让文本垂直居中,只需要让行高=p的高度就可以了;

对于盒子

1、绝对定位,上右下左偏移为0

将要垂直居中的盒子设为绝对定位,然后上右下左的偏移量设置为0,之后margin: auto;即可。
前置条件

  1. 要将盒子设为绝对定位,父元素先要设为相对定位;
  2. 父元素必须要有一个确切的高,如height: 500px;,最好不要是height: 100%;
  3. 如果将父元素的height设置为100%,那么这个父元素的父元素必须要有一个确切的高度。
<head>
	<meta charset="UTF-8">
	<title>垂直居中</title>
	<style type="text/css">
		section{
			position: relative;
			height: 500px;
			border:1px solid blue;
		}

		.middle{
			position: absolute;
			width:100px;
			height:100px;
			border:1px solid red;
			top: 0;
			right: 0;
			bottom: 0;
			left: 0;
			margin: auto;
		}

	</style>
</head>
<body>
	<section>
		<div class="middle">
		</div>
	</section>
</body>

image_1brsu8pdg1gvh15j51edro18t299.png-16kB

2、绝对定位,负外边距

将要垂直居中的盒子设为绝对定位,然后上、左的偏移量设置为50%,之后上外边距设为当前盒子高的一半(负值),左外边距设为当前盒子宽的一半(负值)。
前置条件

  1. 要将盒子设为绝对定位,父元素先要设为相对定位;
  2. 父元素必须要有一个确切的高,如height: 500px;,最好不要是height: 100%;
  3. 如果将父元素的height设置为100%,那么这个父元素的父元素必须要有一个确切的高度。
<head>
	<meta charset="UTF-8">
	<title>垂直居中</title>
	<style type="text/css">
		section{
			position: relative;
			height: 500px;
			border:1px solid blue;
		}

		.middle{
			position: absolute;
			width:100px;
			height:100px;
			border:1px solid red;
			top: 50%;
			left: 50%;
		    margin-left:-50px;
            margin-top:-50px;
		}

	</style>
</head>
<body>
	<section>
		<div class="middle">
		</div>
	</section>
</body>

posted on 2017-10-08 11:07  Yoooshiki  阅读(147)  评论(0编辑  收藏  举报

导航