css或css3元素垂直水平居中

css或css3元素垂直水平居中

本文章提供以下7种垂直水平居中的方法,具体用哪种见仁见智。

1.利用css3的transform属性,同时将它内部的img垂直居中

<div class="transform"><img src="favicon.ico" /></div>
.transform {
			width: 300px;
			height: 300px;
			text-align: center;
			line-height: 300px;
			background: #90EE90;
			margin: 0 auto;
			position: absolute;
			top: 50%;
			left: 50%;
			transform: translate(-50%, -50%);
		}
		
		.transform img {
			width: 50px;
			height: 50px;
			vertical-align: middle;
		}

2.Flex垂直水平居中

<div class="flex">
			Flex垂直水平居中
		</div>
.flex{
			font-size: 25px;
			height: 200px;
			border: 1px solid black;
			display: flex;
			align-items: center;
			justify-content: center;
		}

3.利用position:absolute/fixed,设置left、top、margin-left、margin-top的属性

<div class="three"></div>
.three {
			position: absolute;/*fixed*/
			width: 200px;
			height: 200px;
			top: 50%;
			left: 50%;
			margin-top: -100px;
			margin-left: -100px;
			background: red;
		}

4.利用position:absolute/fixed,设置margin:auto

<div class="four"></div>
.four {
			position: fixed;
			width: 160px;
			height: 160px;
			top: 0;
			right: 0;
			bottom: 0;
			left: 0;
			margin: auto;
			background: pink;
		}


5.利用display:table-cell属性使内容垂直居中

<div class="five">内容垂直居中</div>
.five {
			display: table-cell;
			vertical-align: middle;
			text-align: center;
			width: 120px;
			height: 120px;
			background: purple;
		}


6.利用display:-webkit-box属性

<div class="six">display:-webkit-box属性</div>
.six {
			width: 200px;
			height: 200px;
			display: -webkit-box;
			-webkit-box-pack: center;
			-webkit-box-align: center;
			background: yellow;
			color: black;
		}

7.最高大上的一种,利用:before元素

<div class="seven"><div class="content"></div></div>
 .seven {
			position: fixed;
			display: block;
			top: 0;
			right: 0;
			bottom: 0;
			left: 0;
			text-align: center;
			background: rgba(0, 0, 0, .5);
		}
		
		.seven:before {
			content: '';
			display: inline-block;
			vertical-align: middle;
			height: 100%;
		}
		
		.seven .content {
			display: inline-block;
			vertical-align: middle;
			width: 60px;
			height: 60px;
			line-height: 60px;
			color: red;
			background: yellow;
		}

  • 2
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Let dreams fly

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值