CSS水平垂直居中回顾总结

前言

用了一段时间的 material-ui,都不多本身动手写原生的样式了。但 html, css, js 始终是前端的三大基础,这周忽然想到 CSS 水平居中方案,由于用多了 flexmargin: auto等这类方案解决,在回顾还有还有几种方案能够解决,因而打算温故知新,从新打下代码,写下该文做为笔记。css

html 代码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;
}

下面代码基于上述代码增长,不会再重复写。要实现的效果是让子元素在父元素中水平垂直居中
git

1、flex 布局

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

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

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

2、absolute + 负 margin

该方法适用于知道固定宽高的状况。布局

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

3、absolute + transform

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

4、absolute + margin auto

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

5、absolute + calc

该方法适用于知道固定宽高的状况。flex

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

6、text-align + vertical-align

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

7、table-cell

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

8、Grid

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

9、writing-mode

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


相关文章
相关标签/搜索