居中

2021-12-01  本文已影响0人  樱桃小白菜

行内元素

水平居中

通过文本的水平对齐方式

.dad {
  text-align: center
}

垂直居中

通过文本的行间的距离

.dad {
  height: 100px
}
.son {
  line-height: 100px
}

块级元素

水平居中

.son {
  margin: 0 auto
}

通过 fit-content属性保持在原有宽度时,左右居中

.dad {
  width: fit-content
  margin: 0 auto
}
.son {
  float: left
}

通过 left 向左移动 50% 达到居中

.son {
  position: absolute
  width: 宽度
  left: 50%
  margin-left: -0.5*宽度
}

通过 margin 左右自动居中

.son {
  position: absolute
  width: 宽度
  left: 0
  right: 0
  margin: 0 auto
}

通过 transform 动画配合

.son {
    position: absolute
    left: 50%
    transform: translate(-50%, 0)
}

垂直居中

通过元素的垂直对齐方式

.dad::after, .son {
  display: inline-block;
  vertical-align: middle;
}
.dad::after {
  content: '';
  height: 100%;
}

通过 transform 动画配合

.son {
  position: absolute
  top: 50%
  transform: translate( 0, -50%)
}

通过 table

    .parent {
      width: 500px;
      height: 500px;
      border: 1px solid #000;
      display: table-cell;
      vertical-align: middle;
      text-align: center;
    }

    .son {
      width: 100px;
      height: 100px;
      border: 1px solid #999;
      display: inline-block;
    }

通过 flex

display:flex;
align-item:center

参考

W3C - CSS参考手册

掘金 - 一起搞懂 CSS 水平居中与垂直居中的16个方法

上一篇 下一篇

猜你喜欢

热点阅读