css 置中,css

來源:互聯網
上載者:User

css 置中,css

1、把margin 設為atuo

  margin :簡寫屬性在一個聲明中設定所有外邊距屬性。該屬性可以有 1 到 4 個值。

  具體來說就是把要置中的元素的margin-left和margin-right都設為auto,此方法只能進行水平的置中,且對浮動元素或絕對位置元素無效

<!DOCTYPE html><html><head>   <title>margin 置中</title>   <meta charset="utf-8"><style type="text/css">#test{   width:50px;   height: 50px;   background-color: blue;   margin: auto;}</style></head><body><div id="test"></div></body></html>

 

結果:

2、text-align 置中

  text-align 屬性規定元素中的文本(只能對圖片,按鈕,文字等行內元素(display為inline或inline-block等))的水平對齊。

  該屬性通過指定行框與哪個點對齊,從而設定區塊層級元素內文本的水平對齊。通過允許使用者代理程式調整行內容中字母和字之間的間隔,可以支援值 justify;不同使用者代理程式可能會得到不同的結果。

 

<!DOCTYPE html><html><head>   <title>margin 置中</title>   <meta charset="utf-8"><style type="text/css">#test{   text-align: center}div{    width: 100px;    background-color: rgb(12,110,221);    margin-bottom: 20px;}</style></head><body><div id="test">    測試</div><div >    測試</div></body></html>

 

   結果如下:

  解析:測試1的div 添加了text-align:center 的屬性,故文字置中, 測試2所在div沒有加text-align:center,故預設居左。 但是這裡只是div中的文字置中。

3、使用絕對位置來置中(水平垂直置中)

  這種方式只適用於那些我們已經知道它們的寬度和高度的元素。

  原理:通過把這個絕對位置元素的left或top的屬性設為50%,這個時候元素並不是置中的,而是比置中的位置向右或向左偏了這個元素寬度或高度的一半的距離,所以需要使用一個負的margin-left或margin-top的值來把它拉回到置中的位置,這個的margin值就取元素寬度或高度的一半。

<!DOCTYPE html><html><head>   <title>絕對位置 置中</title>   <meta charset="utf-8"><style type="text/css">body{    margin: 0;    padding: 0;}#test{   width:50px;   height: 50px;   background-color: blue;      position: absolute;   left : 50%;     top:50%;   margin-left: -25px;    /* 寬度的一半 */   margin-top: -25px;     /* 高度的一半 */}</style></head><body><div id="test"></div></body></html>

  結果如下:

 4、另外的絕對位置方式(水平垂直置中)

  只適用於知道高度和寬度的元素。

  只支援IE9+,Google,Firefox等符合w3c標準的現代瀏覽器。

demo:

<!DOCTYPE html><html><head>   <title>絕對位置 置中</title>   <meta charset="utf-8"><style type="text/css">body{    margin: 0;    padding: 0;}#test{   width:50px;   height: 50px;   /* 高度和寬度必須固定 */   background-color: blue;   position: absolute;   left : 0;     top:0;   right: 0;   bottom:0;   margin: auto;}</style></head><body><div id="test"></div></body></html>

 

  結果如下:

   致謝:感謝您的閱讀!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.