溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

csss實(shí)現(xiàn)水平居中的方法

發(fā)布時(shí)間:2020-07-02 11:58:14 來源:億速云 閱讀:374 作者:Leah 欄目:web開發(fā)

這期內(nèi)容當(dāng)中小編將會(huì)給大家?guī)碛嘘P(guān)csss實(shí)現(xiàn)水平居中的方法,文章內(nèi)容豐富且以專業(yè)的角度為大家分析和敘述,閱讀完這篇文章希望大家可以有所收獲。

(1)行內(nèi)元素(文字、圖片、行內(nèi)標(biāo)簽(span)、行內(nèi)塊標(biāo)簽(display:inline-block)):text-align: center,下面以span為例:

<p class="father">
  <!-- 行內(nèi)元素 -->
  <span class="son">hello</span> </p>
.father {
  width: 200px;
  height: 200px;
  border: 1px solid red;
  text-align: center;}

優(yōu)點(diǎn):兼容性好,簡單

缺點(diǎn):text-align具有繼承性,會(huì)影響后代元素

(2)塊級(jí)元素:margin:0 auto

<!-- 相對(duì)于body居中 --><body>
  <!-- 塊級(jí)元素 -->
  <p class="son"></p></body>
.son {
  width: 200px;
  height: 200px;
  border: 1px solid red;
  margin: 0 auto;}

優(yōu)點(diǎn):簡單,兼容性好

缺點(diǎn):寬度必須已知且小于父級(jí)元素

(3)flex實(shí)現(xiàn),設(shè)置主軸方向居中

 <p class="father">
   <span class="son"></span>
 </p>
.father {
  width: 500px;
  height: 100px;
  border: 1px solid red;
  display: flex;
  justify-content: center;}.son {
  width: 100px;
  background-color: turquoise;}

如果是多個(gè)元素可以設(shè)置為:

justify-content: space-around; /* 子元素左右兩邊距離均勻分布 */或justify-content: space-between; /* 最左邊和最右邊元素靠緊父元素,其余均勻 */

優(yōu)點(diǎn):方便,可以實(shí)現(xiàn)自適應(yīng)

缺點(diǎn):兼容性稍微差一點(diǎn),PC端IE10以上支持

(4)絕對(duì)定位實(shí)現(xiàn):子絕父相

 <p class="father">
   <span class="son"></span>
 </p>
 .father {
   width: 500px;
   height: 100px;
   border: 1px solid red;
   position: relative;
 }

 .son {
   position: absolute;
   width: 100px;
   height: 100px;
   background-color: red;
   left: 50%;
   transform: translate(-50%);/* margin-left: -50% */
 }

優(yōu)點(diǎn):優(yōu)點(diǎn)很少,對(duì)于較難實(shí)現(xiàn)居中的元素可以用定位,margin-left兼容性好點(diǎn)

缺點(diǎn):脫離文檔流,代碼多,兼容性稍微差點(diǎn),IE9以上支持transform,而且需要知道寬度值。

上述就是小編為大家分享的csss實(shí)現(xiàn)水平居中的方法了,如果剛好有類似的疑惑,不妨參照上述分析進(jìn)行理解。如果想知道更多相關(guān)知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI