前端div水平居中的几种实现方式

借助display布局

  • 父元素开启display:flex布局,并设置justify-content:center主轴的空隙分布
    • 因为是单行,所以使用align-items:center设置侧轴上的对其方式
<body>
  <style>
    .a{
      width: 200px;
      height: 200px;
      background-color: red;
      display: flex;
      justify-content: center;
      align-items: center;
    }
    .a .a1{
      width: 50px;
      height: 50px;
      background-color: green;
    }
  style>
  <div class="a">
    <div class="a1">div>
  div>
body>

前端div水平居中的几种实现方式_第1张图片

借助flex布局

  • 啊啊啊
<body>
  <style>
    .a{
      width: 200px;
      height: 200px;
      background-color: red;
      display: grid;
    }
    .a .a1{
      width: 50px;
      height: 50px;
      background-color: green;
      justify-self: center;
      align-self: center;
    }
  style>
  <div class="a">
    <div class="a1">div>
  div>
body>

前端div水平居中的几种实现方式_第2张图片

借助绝对定位和盒子模型计算规则

  • 借助这一条规则
margin-left + border-left + padding-lef + width + padding-right + border-right + margin-right = 父元素内容区的宽度

高度和是一样的
  • 文章:
    • https://www.zhihu.com/question/21644198/answer/42702524
    • https://www.w3.org/TR/CSS2/visudet.html#blockwidth
<body>
  <style>
    .a{
      width: 200px;
      height: 200px;
      background-color: red;
      position: relative;
    }
    .a .a1{
      width: 50px;
      height: 50px;
      background-color: green;
      position: absolute;
      top: 0;
      bottom: 0;
      left: 0;
      right: 0;
      margin: auto ;
    }
  style>
  <div class="a">
    <div class="a1">div>
  div>
body>

前端div水平居中的几种实现方式_第3张图片

借助绝对定位和transform

  • top、left、right、bottom设置百分比基于父元素
  • translate的百分比参照自身
<body>
  <style>
    .a{
      width: 200px;
      height: 200px;
      background-color: red;
      position: relative;
    }
    .a .a1{
      width: 50px;
      height: 50px;
      background-color: green;
      position: absolute;
      top: 50%;
      right: 50%;
      left: 50%;
      bottom: 50%;
      transform: translate(-50%,-50%);
    }
  style>
  <div class="a">
    <div class="a1">div>
  div>
body>

前端div水平居中的几种实现方式_第4张图片

你可能感兴趣的:(javascript,HTML,面试,前端,css,html)