目录

1.最简单的方法

2.利用定位

3.定位配合css3位移

4.弹性盒模型

5.网格布局Grid

相信大家在面试的时候也会经常碰到css实现元素居中的方法,下面我介绍5中方法给大家,欢迎大家评论区交流

需求:

给定两个元素,这两个元素是父子级关系

并且两个元素的大小都是不确定的,那么这时候如何让子级在父级中上下左右都居中?(暂且设定父级比子级要大一些)

1.最简单的方法

父元素设置display:flex,子元素 margin: auto,代码如下:

<style>
    .parent {
      width: 300px;
      height: 200px;
      background: rebeccapurple;
      display: flex;
    }
    .child {
      width: 50px;
      height: 50px;
      background: red;
      margin: auto;
    }
  </style>
  <div class="parent">
    <div class="child"></div>
  </div>

css实现元素居中的5种方法

2.利用定位

思路

父级相对定位,子级绝对定位 而四个定位属性的值都设置了0;那么这时候如果子级没有设置宽高,则会被拉开到和父级一样宽高。而现在设置了子级的宽高,所以宽高会按照我们的设置来显示;但是实际上子级的虚拟占位已经撑满了整个父级,这时候再给它一个margin:auto它就可以上下左右都居中了

<style>
    .parent {
      width: 300px;
      height: 200px;
      background: pink;
      position: relative;
    }
    .child {
      width: 50px;
      height: 50px;
      background: gold;
      position: absolute;
      left: 0;
      top: 0;
      right: 0;
      bottom: 0;
      margin: auto;
    }
  </style>
  <div class="parent">
    <div class="child"></div>
  </div>

css实现元素居中的5种方法

3.定位配合css3位移

思路

父级相对定位,子级绝对定位,而top,left这两个属性的如果给百分比;那么这个百分比则是相对于父级的宽高来进行计算的;如果只给定这两个值,则子级的右上角会和父级的中心点对齐,得到下图:这时候则需要进一步操作:css3中的位移属性,则是根据自身来计算百分比的;所以只需要利用这个属性把自身再往左上角各移动50%就可以让子级在父级中上下左右都居中了

<style>
    .parent {
      width: 300px;
      height: 200px;
      background: rgb(203, 192, 255);
      position: relative;
    }
    .child {
      width: 50px;
      height: 50px;
      background: rgb(221, 201, 73);
      position: absolute;
      left: 50%;
      top: 50%;
      transform: translate(-50%,-50%);
    }
  </style>
  <div class="parent">
    <div class="child"></div>
  </div>

css实现元素居中的5种方法

4.弹性盒模型

css3的功劳,没啥技巧,掌握了弹性盒模型就能掌握这个方法,简单粗暴。

<style>
    .parent {
      width: 300px;
      height: 200px;
      background: rgb(203, 192, 255);
      display: flex;
      justify-content: center;
      align-items: center;
    }
    .child {
      width: 50px;
      height: 50px;
      background: rgb(62, 57, 24);
    }
  </style>
  <div class="parent">
    <div class="child"></div>
  </div>

css实现元素居中的5种方法

5.网格布局Grid

这个方法和弹性盒模型一样,简单粗暴,没啥可说的。

<style>
    .parent {
      width: 300px;
      height: 200px;
      background:green;
      display: grid;
      justify-content: center;
      align-items: center;
    }
    .child {
      width: 50px;
      height: 50px;
      background: rebeccapurple;
    }
  </style>
  <div class="parent">
    <div class="child"></div>
  </div>

css实现元素居中的5种方法

欢迎在评论区交流。如果文章对你有所帮助,不要忘了点上宝贵的一赞!

我的博客原文:程序员导航

我的编程导航:程序员导航

前端热门面试题:程序员导航

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。