如何在一个div内使其子div居中的方式4种方式?

##《 在这我为大家总结了下在一个div使其子div居中的方式4种方式,希望可以帮助的大家,》有喜欢的小伙伴,和喜欢交流分享的小伙伴欢迎加我微信:15633050186 小姐姐有惊喜的哦!!!

1.弹性布局

html代码:

<div class="father">
		<div class="son"></div>
	</div>

CSS样式:

.father{
			width:400px;
			height:400px;
			background:black;
   			display: flex;
			justify-content: center;
			align-items:center;  
		}	
		.son{
			width:200px;
			height:200px;
			background:red;
		}

附图:
在这里插入图片描述

2.相对定位

html代码:

<div class="father">
    		<div class="son"></div>
    	</div>

CSS样式:

.father{
		width:400px;
		height:400px;
		background:black;
		position: absolute;
	}	
	.son{
		position: relative;
		top: 100px;
		left: 100px;
		width:200px;
		height:200px;
		background:red;

附图:
是多少是对的是是收到是多少多少

3.相对定位的另一种方式

html代码:

<div class="father">
		<div class="son"></div>
	</div>

CSS样式:

.father{
		width:400px;
		height:400px;
		background:black;
		position: absolute;
	}	
	.son{
		position: relative;
		top: 50%;
		left: 50%;
		margin-top:-100px;     /*子元素宽高的一半 son/2*/
		margin-left: -100px;  /*子元素宽高的一半  son/2*/
		width:200px;
		height:200px;
		background:red;
	}

附图:
在这里插入图片描述

此方法较上一方法容易理解:

html代码:

   <div class="father">
    		<div class="son"></div>
    </div>

CSS样式:

  .father{
    	width:400px;
    	height:400px;
    	background:black;
    	position: absolute;
    }	
    .son{
    	position: relative;
    	margin-top:100px;   
    	margin-left:100px;  
    	width:200px;
    	height:200px;
    	background:red;
    }

附图:
在这里插入图片描述

4.CSS位移

html代码:

<div class="father">
		<div class="son"></div>
	</div>

CSS样式:

.father{
		width:400px;
		height:400px;
		background:black;
		position: absolute;
	}	
	.son{
		position: relative;
		transform: translate(50%,50%);
		width:200px;
		height:200px;
		background:red;
	}

附图:
在这里插入图片描述
喜欢的小伙伴点个赞?吧!!!,欢迎各位大佬的指教!!!! 微信:15633050186

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值