css使容器实现垂直水平居中的几种方法

使子容器在父容器中垂直居中的六种方法.

第一种,使用定位来实现

	.wrap1
			{
				width: 200px;
				height: 200px;
				background-color: #00FFFF;
				position: relative;
			}
			.index1
			{
				width: 50px;
				height: 50px;
				background-color: #008000;
				position: absolute;
				left: 0;
				top: 0;
				right: 0;
				bottom: 0;
				margin: auto;
			}

	<!-- 使用定位 -->
		<div class="wrap1">
			<div class="index1">
				
			</div>
		</div>

第二种,使用定位结合margin来实现

.wrap2
			{
				width: 200px;
				height: 200px;
				background-color: #0FFF00;
				position: relative;
			
			}
			.index2
			{
				width: 50px;
				height: 50px;
				background-color: #008000;
				position: absolute;
				left: 50%;    /*相对父容器宽度距离一半*/
				top: 50%;     /*相对父容器高度一半*/
				margin-left: -25px;    /*当前容器的宽度一半*/
				margin-top: -25px;      /*当前容器的高度一半*/
			}
	<!-- 使用定位结合margin -->
		<div class="wrap2">
			<div class="index2">
				
			</div>
		</div>

第三种,使用transform结合margin实现

			.wrap3
			{
				width: 200px;
				height: 200px;
				background-color: #FF0000;
				
			}
			.index3
			{
				width: 50px;
				height: 50px;
				background-color: #2F2182;
				transform: translate(100px,100px);/*相对父元素的一半高度和宽度*/
				margin-left: -25px;
				margin-top: -25px;
			}

第四种,使用flex布局,针对所有子元素

.wrap4
			{
				width: 200px;
				height: 200px;
				background-color: #000;
				display: flex;
				justify-content: center;
				align-items: center;
			}
			.index4
			{
				width: 50px;
				height: 50px;
				background-color: #FFF;
			}
	<!-- 使用flex布局,针对所有元素 -->
		<div class="wrap4">
			<div class="index4">
				
			</div>
		</div>

使用flex布局,针对单个子元素

	.wrap5
			{
				width: 200px;
				height: 200px;
				background-color: blue;
				display: flex;
				justify-content: center;
			}
			.index5
			{
				width: 50px;
				height: 50px;
				background-color: #FFF;
			    align-self: center;
			}

第六种,使用grid布局(类似于flex布局)

/* grid居中写法 */
			.wrap6
			{
				
			    width: 200px;
			    height: 200px;
			    background-color: salmon;
			    display: grid;
			    justify-content: center;
				align-content: center;
			}
			.index6
			{
				width: 50px;
				height:50px;
				background-color: #0FFF00;
			}
	<!-- grid居中 -->
		<div class="wrap6">
			<div class="index6">
				
			</div>
		</div>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值