發佈日期: 發佈留言

CSS 垂直置中的方法整理

一堆垂直置中的 css 方法,到底要用哪種? 陸續更新中

區塊垂直置中

垂直置中定義:

  • 子元素水平、垂直都是置中
  • 子元素不論父層如何縮放依舊垂直置中

這篇舉例的命名說明:

  • 父層:parent
  • 子元素:child

提醒:可自行在元素跟父層的 css 中先定義背景色、寬高才能看出垂直置中效果。

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

flex

第1種 flex + center:

.parent {
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #e1eb46;
  height: 15rem
}
  • display: flex 加入彈性排版後,加上下列 flex 元素的才有效果
  • justify-content: center X 軸置中
  • align-items: center Y 軸置中

第2種 flex + margin:

.parent {
  display: flex;
  background-color: #e1eb46;
  height: 15rem
}
.child {
  margin: auto;
  width: 3rem;
  height: 3rem;
  background-color: #fcffc9;
}
  • margin: auto 自動分配剩餘空間

Position + Transform

.parent {
  position: relative;
  background-color: #e1eb46;
  height: 15rem
}
.child {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%,-50%);
  width: 3rem;
  height: 3rem;
  background-color: #fcffc9;
}
  • 父層
    • position: relative 讓子元素位置相關於父層。
  • 子元素
    • position: absolute 讓子元素絕對定位
    • top: 50% 離頂端 50% 位置
    • left: 50% 離左端 50% 位置
    • transform: translate(-50%,-50%) 物件的對齊點為自身左上角,所以用 X、Y 軸負向偏移 50% ,讓對齊點為自身中心,才能垂直置中

查看所有的區塊垂直置中 Demo


文字垂直置中

垂直置中定義:

  • 子元素水平、垂直都是置中
  • 子元素不論父層如何縮放依舊垂直置中
css_center_VH_02

這篇舉例的命名說明:

  • 父層:parent
  • 子元素:child

提醒:可自行在元素跟父層的 css 中先定義背景色、寬高才能看出垂直置中效果。

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

flex

.parent {
  display: flex;
  justify-content: center;
  background-color: #e1eb46;
  height: 15rem;
}
.child {
  align-self: center;
}
  • 父層
    • display: flex 加入彈性排版後,加上下列 flex 元素的才有效果
    • justify-content: center X 軸置中
  • 子元素
    • align-self: center 讓子元素本身 Y 軸置中

line height

.parent {
  background-color: #e1eb46;
}
.child {
  text-align: center;
  text-align: -webkit-center; /* Safari and Chrome */
  text-align: -moz-center; /* Firefox */
  text-align: -ms-center; /* IE */
  text-align: -o-center; /* Opera */
  height: 15rem;
  line-height: 15rem;
}
  • 子元素
    • text-align: center 讓子元素本身 X 軸置中
    • 其他的 center 前面放的前綴詞,是確保在其他瀏覽器能呈現
    • line-height: 15rem 跟高度一樣數值的 line-height 可以讓子元素本身 Y 軸置中
發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *