关于css:CSS水平垂直居中回顾总结

3次阅读

共计 1566 个字符,预计需要花费 4 分钟才能阅读完成。

前言

用了一段时间的 material-ui,都很少本人入手写原生的款式了。但 html, css, js 始终是前端的三大根底,这周忽然想到 CSS 程度居中计划,因为用多了 flexmargin: auto 等这类计划解决,在回顾还有还有几种计划能够解决,于是打算温故知新,从新打下代码,写下该文作为笔记。

html 代码

<div class="parent">
  <div class="child"></div>
</div>

css 代码

.parent {
  width: 300px;
  height: 300px;
  background-color: blue;
}
.child {
  width: 100px;
  height: 100px;
  background-color: red;
}

上面代码基于上述代码减少,不会再反复写。要实现的成果是让子元素在父元素中程度垂直居中

一、flex 布局

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

这是最经典的用法了,不过,也能够有另一种写法实现:

.parent {display: flex;}
.child {
    align-self: center;
    margin: auto;
}

二、absolute + 负 margin

该办法实用于晓得固定宽高的状况。

.parent {position: relative;}
.child {
  position: absolute;
  top: 50%;
  left: 50%;
  margin-top: -50px;
  margin-left: -50px;
}

三、absolute + transform

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

四、absolute + margin auto

.parent {position: relative;}
.child {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  margin: auto;
}

五、absolute + calc

该办法实用于晓得固定宽高的状况。

.parent {position: relative;}
.child {
  position: absolute;
  top: calc(50% - 50px);
  left: calc(50% - 50px);
}

六、text-align + vertical-align

.parent {
  text-align: center;
  line-height: 300px; /* 等于 parent 的 height */
}
.child {
  display: inline-block;
  vertical-align: middle;
  line-height: initial; /* 这样 child 内的文字就不会超出跑到上面 */
}

七、table-cell

.parent {
  display: table-cell;
  text-align: center;
  vertical-align: middle;
}
.child {display: inline-block;}

八、Grid

.parent {display: grid;}
.child {
  align-self: center;
  justify-self: center;
}

九、writing-mode

.parent {
  writing-mode: vertical-lr;
  text-align: center;
}
.child {
  writing-mode: horizontal-tb;
  display: inline-block;
  margin: 0 calc(50% - 50px);
}

  • ps:集体技术博文 Github 仓库,感觉不错的话欢送 star,给我一点激励吧~
正文完
 0