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);
}


相關文章
相關標籤/搜索