资讯

精准传达 • 有效沟通

从品牌网站建设到网络营销策划,从策略到执行的一站式服务

【面试题】CSS 中几种最常用的水平垂直居中的方法

CSS 中几种最常用的水平垂直居中的方法

点击打开视频讲解更加详细

创新互联公司坚持“要么做到,要么别承诺”的工作理念,服务领域包括:成都网站建设、做网站、企业官网、英文网站、手机端网站、网站推广等服务,满足客户于互联网时代的榆树网站设计、移动媒体设计的需求,帮助企业找到有效的互联网解决方案。努力成为您成熟可靠的网络建设合作伙伴!

一、使用 margin:auto

当元素有给定的高度以及宽度的时候,使用 margin: auto; 元素仅会水平居中,并不会进行垂直居中。
此时就需要设置元素的 position 为 absolute,父级元素的 position 为 relative,同时元素的上下左右都需要设置为 0。
.box{ width: 200px; height: 200px; background-color: #eee; position: relative; margin-top: 20px; } .center1{ width: 50px; height: 50px; background-color: #00ACED; margin: auto; position: absolute; top: 0; left: 0; right: 0; bottom: 0; }

效果展示:

二、使用 position:absolute

当已经知道了要进行水平垂直居中的元素的宽高时,就可以通过设置 position: absolute 来实现。
但是,使用的同时还需要结合其他属性才完整实现。
因为,单是设置 absolute,上左距离均为一半,就会出现下面这种情况。
很显然可以看到,元素并不是完全居中,仅只有左上角的位置在中心点。

概念图:

因此想要实现元素完全水平垂直居中,在设置了 absolute 定位后,可以设置 margin 值为负,或者使用 calc 来计算,上左距离在 50% 的基础上还要减去元素本身一半的宽高。

margin 值为负或者 calc 计算均是在已知元素宽高的情况下,假设不知道元素的宽高,那么怎么实现水平垂直居中呢?这里就可以使用 transform 属性,通过坐标位移来实现居中。

/* 结合 margin */
.center2{  
	width: 50px;  
	height: 50px;  
	background-color: #7FFFD4;  
	position: absolute;  
	left: 50%;  
	top: 50%;  
	margin-left: -25px;  
	margin-top: -25px;
}
/* 结合 calc 计算*/
.center2{  
	width: 50px;  
	height: 50px;  
	background-color: #7FFFD4;  
	position: absolute;  
	left: calc(50% - 25px)  
	top: calc(50% - 25px);
}
/* 结合 transform */
.center2{
	width: 50px;
	height: 50px;
	background-color: #7FFFD4;
	position: absolute;
	left: 50%;
	top: 50%;
	transform: translate(-50%, -50%);
}

效果展示:

三、使用弹性布局

可以通过弹性布局来设置水平垂直居中,这里需要设置父级元素 display:flex; 还需要设置两个属性,
水平布局 justify-content 以及垂直布局 align-items。
.box2{ background-color: #eee; width: 200px; height: 200px; position: relative; margin-top: 20px ; display: flex; justify-content: center; align-items: center; } .center4{ width: 50px; height: 50px; background-color: #B; }

效果展示:

四、文本水平对齐和行高

前面介绍的是元素如何实现水平垂直居中,下面介绍的是如何将文字进行水平垂直居中。
这第一个方法也是最经常用的,使用文本水平对齐 text-align 和行高 line-height 来实现的。
文字居中
.box3{ background-color: #eee; width: 200px; height: 200px; margin-top: 20px; } .center5{ text-align: center; line-height: 200px; }

效果展示:

五、使用网格布局

第二个方法可以通过网格布局 grid 来实现。而这里通过 grid 有两种方式实现,一种对元素本身属性进行设置,另一种在元素的父级元素中设置。两者看上去内容似乎差不多,不同的是在元素中设置的是 align-self 还要多了一个 margin,父级元素中是 align-items。

/* grid 元素中设置 */
.box4{  
	background-color: #eee;  
	width: 200px;  
	height: 200px;  
	margin-top: 20px;  
	display: grid;
}
.center6{  
	align-self: center;  
	justify-content: center;  
	margin: auto;
}
/* grid 父级元素中设置 */
.box5{  
	background-color: #eee;  
	width: 200px;  
	height: 200px;  
	margin-top: 20px;  
	display: grid;  
	align-items: center;  
	justify-content: center;
}

效果展示:

若对您有帮助,请点击跳转到B站一键三连哦!感谢支持!!!


网站名称:【面试题】CSS 中几种最常用的水平垂直居中的方法
本文网址:http://cdkjz.cn/article/dsojsih.html
多年建站经验

多一份参考,总有益处

联系快上网,免费获得专属《策划方案》及报价

咨询相关问题或预约面谈,可以通过以下方式与我们联系

大客户专线   成都:13518219792   座机:028-86922220