元素水平垂直居中的方法

让某个元素在水平和垂直的方向都居中 内容不限于文字,可能会是图片和其他元素


方法一:定位 + margin负值

<style>
  .father {
    width: 400px;
    height: 400px;
    background-color: pink;
    position: relative;
  }

  .son {
    width: 200px;
    height: 200px;
    background-color: aquamarine;
    position: absolute;
    left: 50%;
    top: 50%;
    margin-left: -100px;  /* 子盒子宽度的一半 */
    margin-top: -100px;   /* 子盒子高度的一半 */
  }
</style>
<div class="father">
  <div class="son"></div>
</div>

方法二:定位 + transform负值

<style>
  .father {
    width: 400px;
    height: 400px;
    background-color: pink;
    position: relative;
  }

  .son {
    width: 200px;
    height: 200px;
    background-color: aquamarine;
    position: absolute;
    left: 50%;
    top: 50%;
   	transform: translate(-50%, -50%);
  }
</style>
<div class="father">
  <div class="son"></div>
</div>

方法三:定位 + margin: auto

<style>
  .father {
    width: 400px;
    height: 400px;
    background-color: pink;
    position: relative;
  }

  .son {
    width: 200px;
    height: 200px;
    background-color: aquamarine;
    position: absolute;
    /* 以下四个属性必须都要写上 */
    left: 0;
    top: 0;
    right: 0;
    bottom: 0;
    margin: auto;
  }
</style>
<div class="father">
  <div class="son"></div>
</div>

方法四:flex布局

<style>
  .father {
    width: 400px;
    height: 400px;
    background-color: pink;
    display: flex;
    justify-content: center; /* 主轴居中 */
    align-items: center; /* 侧轴居中 */
  }

  .son {
    width: 200px;
    height: 200px;
    background-color: aquamarine;
  }
</style>
<div class="father">
  <div class="son"></div>
</div>

方法五:table布局

将父元素设置 display:table-cell 子元素设置 display: inline-block

<style>
  .father {
    width: 400px;
    height: 400px;
    background-color: pink;
    display: table-cell;
    vertical-align: middle;
    text-align: center;
  }

  .son {
    width: 200px;
    height: 200px;
    background-color: aquamarine;
    display: inline-block;
  }
</style>
<div class="father">
  <div class="son"></div>
</div>

方法六:grid网格布局

grid 是较为新的布局方法,具体咱也没学明白

<style>
  .father {
    width: 400px;
    height: 400px;
    background-color: pink;
    display: grid;
    align-items: center;
    justify-content: center;
  }

  .son {
    width: 200px;
    height: 200px;
    background-color: aquamarine;
  }
</style>
<div class="father">
  <div class="son"></div>
</div>

小结

上述方法不知道元素大小 但仍然可以实现水平垂直居中的有

  1. 定位 + transform负值
  2. 定位 + margin: auto
  3. flex布局
  4. table布局
  5. grid网格布局

行内元素的居中布局

水平居中

  1. text-align: center
  2. 父元素 display: flex justify-content: center

垂直居中

  1. 单行文本:height = line-height
  2. 多行文本:disaply: table-cell; vertical-align: middle

块级元素居中布局

水平居中

  1. margin: 0 auto
  2. 定位 + left: 50% + transform: translateX(-50%);
  3. 定位 + left: 50% + margin-left: 负的自己宽度一半;

垂直居中

  1. 定位 + top: 50% + transform: translateY(-50%);
  2. 定位 + top: 50% + margin-top: 负的自己宽度一半
  3. flex布局
Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐