css 垂直居中

垂直居中

  1. 行内元素,可以设置line-height 与父级 height 相等
  2. 设置 margin/padding 居中
  3. flex 居中 设置 align-items:center
  4. 绝对定位居中

案例:

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>垂直居中案例</title>
	<style type="text/css">
		* {
			margin: 0;
			padding: 0;
			box-sizing: border-box;
		}
		.box{
			width: 200px;
			height: 200px;
			border: 1px solid #a124aa;
			margin: 0 auto;
		}
		.box>.main{
			width: 50px;
			height: 50px;
			background-color: aquamarine;
		}
		/* 上方是公共样式 */
		/* 让main在大盒子里居中 */
		/* 一 */
		.box1>p{
			line-height: 200px;
		}
		/* 方式二 */
		.box2{
			padding-top: 75px;
		}
		/* 方式三 */
		.box3{
			display: flex;
			justify-content: space-between;
			align-items: center;
		}
		/* 方式四 */
		.box4{
			position: relative;
		}
		.box4>.main{
			position: absolute;
			top: 0;     /* 用于垂直居中 */
			bottom: 0; /* 用于垂直居中 */
			right: 0;
			left: 0;
			margin: auto;
		}
	</style>
</head>
<body>
	<div class="box box1">
		<!-- 垂直居中    内联元素span   和  块元素 p -->
		<p>123</p>
	</div>
	<div class="box box2">
		<!-- 垂直居中  方式二 -->
		<p class="main"></p>
	</div>
	<div class="box box3">
		<!-- 垂直居中  方式三 -->
		<p class="main"></p>
		<span>1234</span>
	</div>
	<div class="box box4">
		<!-- 垂直居中  方式四 -->
		<p class="main"></p>
	</div>
	
</body>
</html>

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值