css 上下左右居中的几种方法

html结构

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

1.父元素宽高固定,子元素宽高固定。那么子元素可以通过上、左右的固定margin-left: (父元素宽度 - 子元素宽度)/2、margin-top: (父元素高度 - 子元素高度)/2值实现居中

.father{
	width: 600px;
	height: 400px;
	border: 1px solid #000;
	background-color: #f0f0f0
}
.son{
	width: 100px;
	height: 100px;
	background-color: blue;
	margin-left: 250px;
	margin-top: 150px;
}

2.父元素宽度是不固定的高度固定,此时子元素可以 margin-left:automargin-right:auto

既我们熟悉的 margin: 0 auto

.father{
	height: 400px;
	border: 1px solid #000;
	background-color: #f0f0f0;
}
.son{
	width: 100px;
	height: 100px;
	background-color: blue;
	margin: 150px auto 0 auto;
}

3.父元素宽高不固定(涉及元素高度百分比问题,如果元素高度设置为百分数,那么此元素的父元素必须固定高度),此处父元素以vh为例子,子元素利用 calc 函数计算获取居中margin-top值(注意calc函数的写法,括号内的计算符号两边必须有空格

.father{
	height: 100vh;
	border: 1px solid #000;
	background-color: #f0f0f0;
}
.son{
	width: 100px;
	height: 100px;
	background-color: blue;
	margin-left: auto;
	margin-right: auto;
	margin-top: calc(50vh - 50px);
}

4.父元素position: relative;宽高无所谓。子元素position: absolute;利用margin-left:-50px (负的居中元素宽度的一半,如margin-top:-50px(负的居中元素高度的一半,此处例子子元素的宽高均为100px实用时注意具体计算);矫正

.father{
	position: relative;
	height: 400px;
	border: 1px solid #000;
	background-color: #f0f0f0;
	box-sizing: border-box;
}
.son{
	position: absolute;
	background-color: blue;
	width: 100px;
	height: 100px;
	left: 50%;
	top: 50%;
	margin-left: -50px;
	margin-top: -50px;
}

5.还是position定位,子元素利用css3 transform: translate(-50%,-50%);偏移实现位置矫正

.father{
	position: relative;
	height: 400px;
	border: 1px solid #000;
	background-color: #f0f0f0;
	box-sizing: border-box;
}
.son{
	position: absolute;
	background-color: blue;
	width: 100px;
	height: 100px;
	left: 50%;
	top: 50%;
	transform: translate(-50%,-50%);
}

6.还是position,父元素大小无所谓。子元素上下左右位置均设置为0,margin:auto

.father{
	position: relative;
	height: 400px;
	border: 1px solid #000;
	background-color: #f0f0f0;
}
.son{
	position: absolute;
	background-color: blue;
	width: 100px;
	height: 100px;
	margin: auto;
	left: 0;
	top: 0;
	right: 0;
	bottom: 0;
}

7.flex,父元素大小无所谓,子元素大小无所谓

.father{
	display: flex;
	justify-content: center;
	align-items: center;
	height: 400px;
	border: 1px solid #000;
	background-color: #f0f0f0;
	box-sizing: border-box;
}
.son{
	background-color: blue;
	width: 100px;
	height: 100px;
}

8. 利用子元素display: inline-block;行内块级元素特性。

父元素高度固定且行高等于自身高度;

.father{
	height: 400px;
	line-height: 400px;
	text-align: center;
	font-size: 0;
	border: 1px solid #000;
	background-color: #f0f0f0;
}
.son{
	display: inline-block;
	background-color: blue;
	width: 100px;
	height: 100px;
	vertical-align: middle;
}

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值