CSS 居中

一. 水平居中

  1. margin: 0 auto
<div class="box"></div>

<style>
.box {
  width: 200px;
  height: 100px;
  margin: 0 auto;
  background-color: pink;
}
</style>
  1. 當子元素 display: inline-block 時,父元素 text-align: center,可控制子元素水平居中。
<div class="wrap">
  <div class="box"></div>
</div>

<style>
.wrap {
  text-align: center;
}
.box {
  display: inline-block;
  width: 100px;
  height: 100px;
  background-color: pink;
}
</style>

text-align: center 在塊級父容器中讓行內元素居中,inline/inline-block/inline-table/inline/flex 等類型的元素實現居中。

二. 垂直居中

  1. 單行,對于單行行內或文本元素,只需為它們添加等值的 padding-toppadding-bottom

  2. 在已知文本不會換行的時候,可以 line-height = height 來實現垂直居中。

  3. 多行文本垂直居中
    3.1 方法一



    3.2 方法二:使用 flex

.box {
  display: flex;
  align-items: center;
  width: 100px;
  height: 100px;
  background-color: #ccc; 
}
  1. 當父元素沒有固定高度時,可以采用 幽靈元素(ghost element)的非常規解決方式:在垂直居中的元素上添加偽元素,設置偽元素的高等于父元素的高,然后為子元素添加 vertical-align: middle;
    // 待定

三. 水平垂直居中

絕對定位元素的水平垂直居中

  1. 寬高固定,絕對定位,top: 50%; left: 50%; 左上 margin 為自身寬高一半
<div class="box"></div>

<style>
.box {
  width: 200px;
  height: 100px;
  position: absolue;
  left: 50%;
  top: 50%;
  margin-top: -50px;
  margin-left: -100px;
  background-color: pink;
}
</style>
  1. 同上,使用 css3 里的 transform 代替 margin。可以不設寬高。
<div class="box"></div>

<style>
.box {
  position: absolue;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  background-color: pink;
}
</style>
  • transform 里的 translate偏移的百分比值是相對于自身大小的

  • translate() 方法,根據 左(X軸)頂部(Y軸) 位置給定的參數,從當前元素位置移動,如:translate(50px,100px)是從左邊元素移動 50 個像素,并從頂部移動 100 像素。

  1. margin:auto
.box {
  position: absolute;
  background: red;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  margin: auto;
  width: 200px;
  height: 100px;
}

利用 flex 布局的水平垂直居中

需要注意,flex 垂直居中相對于父元素高度。

<div class="wrap">
   <div class="box"></div>
</div>

<style>
.wrap {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100vh;
}

.box {
  width: 200px;
  height: 100px;
  background-color: red;
}
</style>

利用 grid 布局的水平垂直居中

方法一:父元素設置 display: grid; justify-items: center; align-items: center;
方法二:父元素設置 display: grid;,子元素設置 justify-self: center; align-self: center;

.wrap {
  display: grid;
  height: 100vh;
  background-color: #ee3;
/*   justify-items: center;
  align-items: center; */
}
.box {
  background-color: #c9c;
  width: 100px;
  justify-self: center;
  align-self: center;
}

參考資料 :
小tip: margin:auto實現絕對定位元素的水平垂直居中

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • 問答題47 /72 常見瀏覽器兼容性問題與解決方案? 參考答案 (1)瀏覽器兼容問題一:不同瀏覽器的標簽默認的外補...
    _Yfling閱讀 13,790評論 1 92
  • 收聽音頻,戳鏈接,舊號itclan已暫停使用,歡迎關注微信itclanCoder公眾號可收聽更多音頻 前言 關于網...
    itclanCoder閱讀 8,204評論 3 30
  • 選擇qi:是表達式 標簽選擇器 類選擇器 屬性選擇器 繼承屬性: color,font,text-align,li...
    wzhiq896閱讀 1,792評論 0 2
  • 選擇qi:是表達式 標簽選擇器 類選擇器 屬性選擇器 繼承屬性: color,font,text-align,li...
    love2013閱讀 2,328評論 0 11
  • 起因 今天早晨坐享的時候,發現心情不太正常,是一種類似于煩惱的東西……對,是焦慮與不耐煩。睜開眼之后想記錄下來,卻...
    一般的路人丙閱讀 2,086評論 0 0