全国服务热线:400-6263-721

位置:南宁达内IT教育培训学校 > 学校动态 > CSS 中几种常用的水平垂直居中的方法

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

来源:南宁达内IT教育培训学校时间:2022/7/26 15:40:41

  CSS 是前端里面的基础之一,也是非常重要的一部分,它往往决定了你所做出来的网页页面是否美观。在设计网页页面的过程中,总会有将元素或者文字进行水平垂直居中的要求。下面就为大家介绍 CSS 中几种常用到的水平垂直居中的方法。

  一、使用 margin:auto

  当元素有给定的高度以及宽度的时候,使用 margin: auto; 元素仅会水平居中,并不会进行垂直居中。此时就需要设置元素的 position 为 absolute,父级元素的 position 为 relative,同时元素的上下左右都需要设置为 0。

  HTML 代码

  CSS 代码

  .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 属性,通过坐标位移来实现居中。

  CSS 代码

  /* 结合 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%);

  }

领取试听课
每天限量名额,先到先得

尊重原创文章,转载请注明出处与链接:http://www.peixun360.com/1658/news/549206/违者必究! 以上就是南宁达内IT教育培训学校 小编为您整理 CSS 中几种常用的水平垂直居中的方法的全部内容。

温馨提示:提交留言后老师会第一时间与您联系!热线电话:400-6263-721