CSS置中問題

來源:互聯網
上載者:User

標籤:通過   ges   情況   寬度   自己   form   元素   方法   四種方法   

Hello!我是super喵二!剛剛在寫一個音樂播放器,其中用到ul沒有設定寬高,由li撐起,然後需要置中顯示在ul的父級div中。剛剛突然忘記了,然後查了下,最後出現置中效果,那就順便總結下置中問題吧~~~

一、水平置中

1、行內元素(文字、圖片、連結等):

  text-align: center;//對inline,inline-block,inline-table有效

2、塊元素(div/p等):

   margin: 0px auto;//無論寬度是否已知

(不過加一句,就是開頭的問題,我只需要設定ul的display:inline-block,就實現置中了,這個問題還在思考,不過建議最好將沒有設定寬的區塊層級元素設為inline-block,再將其父元素添加text-align:center;)

3、多個區塊層級元素

  如果有多個塊元素需要水平置中時,有兩種辦法可以實現。一種是藉助inline-block,另一種是藉助flex。,設定塊元素display:inline-block,其父元素水平置中:

 .div1 {        text-align: center;    }     .div1 div2 {        display: inline-block;    }

用flex的話需要給塊的父元素添加如下樣式:

 .div1 {        display: flex;        justify-content: center;    }

二、垂直置中

1、行內元素:

  單行的行內元素:一種方法可以設定padding-top與padding-bottom的值相等來實現置中;另一種方法是知道高度,設定line-height=height。

  多行的行內元素可以考慮四種方法:

      one:設定padding-top與padding-bottom的值相等

      two:萬能的flex布局{display: flex;justify-content: center; flex-direction: column; height: 400px;}

      three:vertical-align,這種用法才開始接觸css時,我經常用但是沒有效果,後來才發現要這樣用呀(基本用在display為table裡)

                   .div1 {display: table;}

                   .div1>div2 { display: table-cell;vertical-align: middle;}

      four:最後一種方法是在網上看到的:直接截個圖吧:

                                                                               

 

2、區塊層級元素:

   區塊層級元素主要是通過定位設定margin,padding等:

      已知div2的高度時,假設相對其父元素是position:absolute

       { position: absoulte;top: 50%; height: 100px;margin-top: -70px; //這裡70px是height*1/2 + padding padding: 20px;}

     塊元素高度不知道時

        {transform: translateY(-50%);             top: 50%;             position: absoulte;} 

      萬能的flex布局,和水平置中類似,只需要再加一句話:flex-direction: column;就ok了(flex布局還是蠻不錯的,大家可以經常使用哇,菜鳥教程上都說了得到所有瀏           覽器的支援了喲)

三、水平垂直置中:

   就是將以上一些組合使用就是了。

      比如flex布局,只需要加一句:align-items: center;     

 {  position: absoulte;    top: 50%;        left: 50%;        margin: -120px 0px 0px -220px;    //height一半,width一半,另外加上padding值          height: 200px;        width: 400px;        padding: 20px; 
}

{
  top: 50%;      left: 50%;      transform: translate(-50%, -50%);  
}
當然本文有自己的總結,也有從大神的部落格中轉載一些,具體情況具體討論,大家多試試,就知道了~~~~~~~~~~如有錯誤/補充,歡迎提出!!!

CSS置中問題

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.