CSS垂直居中的几种方法

方法有很多,这里简述四种。
1.利用vertical-align进行居中。
2.用定位。
3.用弹性盒。
4.用网格布局。
一、vertical-align
给要居中元素添加标尺;或转为table-cell类型。
用标尺:

<div class="wrap">
	<div class="box">Hello World!</div><span></span>
</div>
.wrap{
	width: 300px;
	height: 300px;
	background: #ffff7f;
	text-align: center;
}
.box{
	display: inline-block;
	background: #55ffff;
	vertical-align: middle;
}
span{
	display: inline-block;
	width: 0;
	height: 100%;
	vertical-align: middle;
}

效果图:
在这里插入图片描述
用table-cell:
可以给父元素设为table,子元素设为table-cell(注释内容);也可以给父元素设为table-cell,子元素用margin水平居中;
在这里用的是父元素设置table-cell:

<div class="wrap">
	<div class="box">Hello World!</div>
</div>
.wrap{
	width: 300px;
	height: 300px;
	background: #ffff7f;
	text-align: center;
	display: table-cell;
	vertical-align: middle;
	/* display: table; */
}
.box{
	background: #55ffff;
	width: 100px;
	margin: 0 auto;
	/* display: table-cell;
	vertical-align: middle; */
}

效果图:
在这里插入图片描述
二、定位
让子元素相对父元素绝对定位,用margin(注释内容)需有固定宽高;或translate进行居中。

<div class="wrap">
	<div class="box">Hello World!</div>
</div>
.wrap{
	width: 300px;
	height: 300px;
	background: #ffff7f;
	position: relative;
}
.box{
	background: #55ffff;
	position: absolute;
	/* width: 100px;
	height: 20px;
	left: 0;right: 0;top: 0;bottom: 0;
	margin: auto; */
	top: 50%;left: 50%;
	transform: translate(-50%,-50%);
}

效果图同上。

三、弹性盒
父元素设为弹性盒,设水平垂直居中属性,也能达到该效果。
justify-content主轴方向对齐方式;align-items侧轴方向对齐方式。
CSS代码:

.wrap{
	width: 300px;
	height: 300px;
	background: #ffff7f;
	display: flex;
	justify-content: center;
	align-items: center;
}
.box{
	background: #55ffff;
}

四、网格布局
所用属性:
place-items: 复合式写法
align-items: start | end | center | stretch; 垂直
justify-items: start | end | center | stretch; 水平
属性值:
start:对齐单元格的起始边缘。
end:对齐单元格的结束边缘。
center:单元格内部居中。
stretch:拉伸,占满单元格的整个宽度(默认值)。
CSS代码:

.wrap{
	width: 300px;
	height: 300px;
	background: #ffff7f;
	display: grid;
	place-items: center center;
}
.box{
	background: #55ffff;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值