首頁  >  文章  >  web前端  >  在HTML中關於元素居中有哪些需要注意的事項

在HTML中關於元素居中有哪些需要注意的事項

php中世界最好的语言
php中世界最好的语言原創
2018-02-22 09:27:301723瀏覽

這次帶給大家在HTML中關於元素居中有哪些需要注意的事項,在HTML中關於元素居中需要注意的事項有哪些,下面就是實戰案例,一起來看一下。

不使用定位

    水平居中:text-align = center;(可繼承)

    豎直居中:margin:0 auto;(#    豎直居中:margin:0 auto;(區塊級元素)

    其他居中:1.文字居中:父元素設定高子元素設定高line-height=height(父元素)

        圖片   居中:  vertical-aign:middle ;  <-- 必須放在圖片元素中

.first{
    width: 300px;
    height: 100px;
    background-color: black;
    color: white;
    text-align: center;
    margin: 0 auto; //针对块级元素
  }
<div class="first">
不使用定位(1)
</div>
.second{
    width: 300px;
    height: 100px;
    background-color: green;
  }
  .s_child{
    width: 150px;
    line-height: 100px;
  }
<div class="second">    
<div class="s_child">   
   不使用定位(2)    
</div> 
</div>

 2.定位居中

  a.父元素高度固定 元素高度固定 與相對定位

    子元素:

絕對定位

        top:50%(父元素高度的一半)## #   top:50%(父元素高度的一半)## #   ##        margin-top:自己的高度一半;(加負號)

        rree# .父元素高度不固定

.dw_one{
      width: 600px;
      height: 300px;
      position: absolute;
      background: black;
    }
    .dw_one_child{
      background: white;
      position: relative;
      width: 50px;
      height: 50px;
      top: 50%;
      left: 50%;
      margin-top: -25px;
      margin-left: -25px;
    }
    <div class="dw_one">
    <div class="dw_one_child">
      a    
    </div>
    </div>

 3.關於多行文字的居中

    使用display:table; display:table-cell;

    vertical-align :middle; 居中

.wrapper{
      width: 600px;
      height: 600px;
    }
    .dw_two{
      width: 100%;
      height: 100%;
      position: absolute;
      background: black;
    }
    .dw_two_child{
      background: white;
      position: relative;
      top: 50%;
      left: 50%;
      width: 100px;
      height: 100px;
      transform:translate(-50%, -50%);
      -moz-transform:translate(-50%, -50%);
      -ms-transform:translate(-50%, -50%);
      -o-transform:translate(-50%, -50%);
      -webkit-transform:translate(-50%, -50%);
    }
    <div class="wrapper">
  <div class="dw_two">
      <div class="dw_two_child">
        a
      </div>
  </div>
</div>

相信看了這些案例你已經掌握了方法,更多精彩請關注php中文網其它相關文章!

相關閱讀:

怎麼實作HTML的仿命令列介面

meta name="" content="應如何使用

以上是在HTML中關於元素居中有哪些需要注意的事項的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn