【css 如何实现盒子垂直居中】 原创

xjj前端妹_雅
发布于 2022-5-16 10:27
浏览
0收藏

文章目录


<hr style=" border:solid; width:100px; height:1px;" color=#000000 size=1">

前言

<font color=#333 >由于flex布局的实用性和通用性,我们往往会忘记传统方法下如果去实现一个盒子脱离了flex后的“垂直居中”效果,所以本篇文章目的在于记录这些我们容易遗忘的小知识点。</font>

<hr style=" border:solid; width:100px; height:1px;" color=#000000 size=1">

一、利用display:flex

<font color=#333 >原理就是定位中心点是盒子的左上顶点,所以定位之后我们需要回退盒子一半的距离。

.parent{
	display:flex;
	justify-content:center;
	align-items:center;
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.

二、利用定位(常用方法,推荐)

<font color=#333 >原理就是定位中心点是盒子的左上顶点,所以定位之后我们需要回退盒子一半的距离。计算方法:父盒子高度或者宽度的一半减去子盒子高度或者宽的的一半。

.parent{
	position:relative;
	border: 1px solid #f00;
	width: 100px;
	height: 100px;
	box-sizing: border-box;
	margin: 100px;
}
.child{
	position:absolute;
	top:50%;
	left:50%;
	margin-top:-25px;
	margin-left:-25px;
	width: 50px;
	height: 50px;
	line-height: 50px;
	border: 1px solid yellow;
	text-align: center;
	box-sizing: border-box;
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.

三、计算父盒子与子盒子的空间距离(这跟方法一是一个道理)

<font color=#333 >计算方法:父盒子高度或者宽度的一半减去子盒子高度或者宽的的一半。

.parent{
	position:relative;
	border: 1px solid #f00;
	width: 100px;
	height: 100px;
	box-sizing: border-box;
	margin: 100px;
}
.child{
	margin-top:25px;
	margin-left:25px;
	width: 50px;
	height: 50px;
	line-height: 50px;
	border: 1px solid yellow;
	text-align: center;
	box-sizing: border-box;
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.

四、利用display:table-cell

.parent{
	display:table-cell;
	vertical-align:middle;
	text-align:center;
}
.child{
	display:inline-block;
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.

五、利用transform

.parent{
	position:relative;
}
.child{
	position:absolute;
	top:50%;
	left:50%;
	transform:translate(-50%,-50%);
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.

六、利用calc计算

(父元素高-子元素高)÷ 2

.parent{
	position:relative;
	border: 1px solid #f00;
	width: 100px;
	height: 100px;
	box-sizing: border-box;
	margin: 100px;
}
.child{
	width: 50px;
	height: 50px;
	line-height: 50px;
	border: 1px solid yellow;
	text-align: center;
	box-sizing: border-box;
	position:absolute;
	top:calc(25px);
	left:calc(25px);
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.

©著作权归作者所有,如需转载,请注明出处,否则将追究法律责任
1
收藏
回复
举报
1


回复
    相关推荐