小div在大div中水平垂直居中方法(div都有固定的大小)

最终效果图:

HTML代码:

<body>
	<div id="parent">
		<div id="child"></div>
	</div>
</body>

方法一:绝对定位与负外边距

儿子绝对定位,父亲相对定位,先定位到父亲的宽高一半的位置,再上和左各负margin自身的一半。

#parent {
	height: 200px;
	width: 200px;
	position: relative;	/*使其充当儿子的定位环境*/
	background-color: red;
}
#child {
	height: 100px;	
	width: 100px;
	position: absolute;	
	top: 50%;	
	left: 50%;
	margin-top:-50px;	/*使向上偏移自身一半*/
	margin-left:-50px;	/*使向左偏移自身一半*/
	background-color: orange;
}

方法二:绝对定位与自动外边距

儿子绝对定位,父亲相对定位,外边距自动。

#parent {
	height: 200px;
	width: 200px;
	position: relative;	/*使其充当儿子的定位环境*/
	background-color: red;
}
#child {
	height: 100px;	
	width: 100px;
	position: absolute;	
	top: 0;	
	bottom: 0;
	left: 0;
	right: 0;
	margin: auto;	/*外边距自动*/
	background-color: orange;
}

方法三:绝对定位与transform:translate();

与负margin-left和margin-top(方法一)实现居中不同的是,margin-left必须知道自身的宽高(负自身已知宽高的一半),而translate可以在不知道宽高的情况下进行居中,tranlate()函数中的百分比是相对于自身宽高的百分比,所以能进行居中。

#parent {
	height: 200px;
	width: 200px;
	position: relative;
	background-color: red;
}
#child {
	height: 100px;	
	width: 100px;
	position: absolute;
	top: 50%;
	left: 50%;
	transform: translate(-50%, -50%);	/*向左(上)平移自身50%的宽度(高度)*/
	background-color: orange;
}

方法四:使用弹性布局flex

Flex布局语法教程:https://www.runoob.com/w3cnote/flex-grammar.html

#parent {
	height: 200px;
	width: 200px;
	display: flex;
	justify-content: center;	/*水平居中*/
	align-items: center;		/*垂直居中*/
	background-color: red;
}
#child {
	height: 100px;	
	width: 100px;
	background-color: orange;
}

 

 

 

 

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值