垂直居中的六种方案

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
	<style type="text/css">
		/*方案一:知道宽度的情况下 absolute+margin负值*/
		/*.parent { 
			width:400px;
			height:400px;
			background: red;
			position: relative;
		}
		.child {
		  position: absolute;
		  left:50%;
		  top:50%;
		  background: blue;
		  width:50px;
		  height:50px;
		  margin-left:-25px;
		  margin-top:-25px;
		}*/

		/*方案二:不知道宽高的情况下 absolute+transform*/
		/*
		.parent { 
			width:400px;
			height:400px;
			background: red;
			position: relative;
		}
		.child {
		  position: absolute;
		  left:50%;
		  top:50%;
		  transform: translate(-50%,-50%);
		}*/

		/*方案三:position+margin:auto*/
		/*
		.parent { 
			width:400px;
			height:400px;
			background: red;
			position: relative;
		}
		.child {
		  width:80px;
		  height:40px;
		  background:yellow;
		  position:absolute;
		  left:0;
		  top:0;
		  right:0;
		  bottom:0;
		  margin:auto;
		}*/
		
		/*方案四:多行文本的垂直居中 display:table-cell+vertical-align:middle;*/
		/*.parent {
			height: 300px;
			width: 400px;
			border: 1px solid red;
			display: table-cell;
			vertical-align: middle;
			text-align: center;
		}
		.child {
			display: inline-block;
			width: 50px;
			height: 50px;
			background: blue;
		}*/
		
		/*方案五:display: flex*/
		/*.parent {
		  width:400px;
		  height:200px;
		  background:red;
		  display: flex;
		  justify-content:center;
		  align-items:center;
		}
		.child {
		  height:100px;
		  width:100px;
		  background:green;
		}*/

		/*方案六:伪元素*/
		.parent {
		  width:200px;
		  height:200px;
		  background:red;
		  text-align: center;
		}
		.child {
			height:100px;
		  width:100px;
		  background:yellow;
		  display: inline-block;
		  vertical-align: middle;
		}
		.parent:before {
			content: "";
			height: 100%;
			vertical-align: middle;
			display: inline-block;
		}
	</style>
</head>
<body>
	<!-- CSS水平垂直居中解决方案(6种) -->
	<!-- 方案一:知道宽度的情况下 absolute+margin负值 -->
	<div class="parent">
	  <div class="child">child</div>
	</div>
</body>
</html>

效果展示 输入图片说明

转载于:https://my.oschina.net/shuaihong/blog/1625961

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值