CSS 多种方式实现元素居中

2021-01-04  本文已影响0人  MercuryWang

1. 固定宽高元素

<div class="wrapper">
      <div class="box fixed-size"></div>
</div>
.wrapper {
 position: relative;
 width: 200px;
 height: 200px;
 background: goldenrod;
}
.fixed-size {
 width: 100px;
 height: 100px;
 background-color: orangered;
}

1.1 absolute + -margin

.box {
  position: absolute;
  top: 50%;
  left: 50%;
  margin-left: -50px;
  margin-top: -50px;
}

另补充,使用 calc 方法也可以实现,改造如下:

{
 /* before */
top: 50%;
left: 50%;
margin-left: -50px;
margin-top: -50px; 
 /* after */
top: calc(50% - 50px);
left: calc(50% - 50px);
}

1.2 absolute + margin auto

.box {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  margin: auto;
}

2. 不固定宽高元素

<div class="wrapper">
      <div class="box">inner text</div>
</div>
.wrapper {
  width: 200px;
  height: 200px;
  border: goldenrod 1px solid;
}
.box {
  background: orangered;
}

2.1 absolute + transform

.wrapper {
  position: relative;
}
.box {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

2.2 line-height

.wrapper {
  line-height: 200px;
  text-align: center;
  font-size: 0px;
}
.box {
  font-size: 16px;
  display: inline-block;
  vertical-align: middle;
  line-height: initial;
  text-align: left; /* 修正文字 */
}

2.3 使用 table

<table>
  <tbody>
    <tr>
      <td class="wrapper">
        <div class="box">inner text</div>
      </td>
    </tr>
  </tbody>
</table>
.wrapper {
  text-align: center;
}
.box {
  display: inline-block;
}

2.4 css-table

不适用 table 元素的情况:

  .wrapper {
    width: 200px;
    height: 200px;
    border: goldenrod 1px solid;
  }
  .box {
    background: orangered;
  }
  .wrapper {
    display: table-cell;
    text-align: center;
    vertical-align: middle;
  }
  .box {
    display: inline-block;
  }

2.5 flex

.wrapper {
    display: flex;
    justify-content: center;
    align-items: center;
}

2.6 grid

.wrapper {
  display: grid;
}
.box {
  align-self: center;
  justify-self: center;
}
上一篇下一篇

猜你喜欢

热点阅读