讓元素居中的幾種方法

一、讓元素水平居中

1.想要一個(gè)塊級(jí)元素在其包含元素內(nèi)居中,可以將此塊級(jí)元素的左、右外邊距的值設(shè)為auto。

html代碼:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
  <div class="box1">
    <p class="box2">
      This is a paragraph with a fixed width,
      and left and right margins set to auto,
      So it's centered.
    </p>
  </div>
</body>
</html>

CSS代碼:

.box1 {
  background-color:pink;
  width:400px;
  height:100px;
}

.box2 {
  background-color:green;
  width:300px;
  height:50px;
  margin-left:auto;
  margin-right:auto;
}

Output:


output1.png

2.想要一個(gè)inline元素、或inline-block元素在其包含元素內(nèi)居中,可以將其被包含元素設(shè)置為 text-align:center。

html代碼:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
  <div class="box1">
    <p class="box2">
      This is a paragraph with a fixed width,
      and left and right margins set to auto,
      So it's centered.<br>
    </p>
    <p class="box3">  <a href="hicc.me">想了解更多請(qǐng)點(diǎn)擊。</a>
    </p>
  </div>
</body>
</html>

CSS代碼:

.box1 {
  background-color:pink;
  width:500px;
  height:200px;
}

.box2 {
  background-color:green;
  width:450px;
  height:80px;
  margin-left:auto;
  margin-right:auto;
}

.box3 {
  width:400px;
  background-color:blue;
  height:80px;
  text-align:center;
}

a {
  background-color:yellow; 
}

Output:

output2.png

二、讓元素垂直居中

在transform: translateY的幫助下我們可以使用三行CSS代碼讓任何甚至不知道高度的元素垂直居中。CSS的transform屬性常用來旋轉(zhuǎn)和縮放元素,現(xiàn)在我們可以使用它的translateY函數(shù)垂直對(duì)齊元素。
垂直居中通常的做法是使用絕對(duì)定位或者設(shè)置行高,但是這兩種方案的弊端是要么需要你知道元素的高度,要么只能作用于單行文本(注:inline或者inline-block元素)。

代碼如下:

.element { 
   position: relative; 
   top: 50%; 
   transform: translateY(-50%); 
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 問答題47 /72 常見瀏覽器兼容性問題與解決方案? 參考答案 (1)瀏覽器兼容問題一:不同瀏覽器的標(biāo)簽?zāi)J(rèn)的外補(bǔ)...
    _Yfling閱讀 14,168評(píng)論 1 92
  • 收聽音頻,戳鏈接,舊號(hào)itclan已暫停使用,歡迎關(guān)注微信itclanCoder公眾號(hào)可收聽更多音頻 前言 關(guān)于網(wǎng)...
    itclanCoder閱讀 8,353評(píng)論 3 30
  • 還有幾天就是農(nóng)歷新年了,于我們而言這是個(gè)舉國歡慶、闔家團(tuán)員的大日子。提前祝各位朋友新年快樂,家人健康。言歸正傳,借...
    崔小叨閱讀 863評(píng)論 1 11
  • 絕對(duì)想不到的是,此時(shí)此刻,他正在電話的另一端。做著他應(yīng)聘公司出的考題數(shù)據(jù)。 我進(jìn)屋,媽媽說,是要打電話嗎?不是,我...
    KinJ閱讀 362評(píng)論 0 0
  • 最終目標(biāo)希望完成如下幾個(gè)功能: (1)登錄校園網(wǎng) (2)登出校園網(wǎng) (3)查詢當(dāng)前網(wǎng)絡(luò)狀態(tài) (4)查詢流量、帳戶余...
    胡哈哈哈閱讀 837評(píng)論 0 1

友情鏈接更多精彩內(nèi)容