css 垂直置中的一些方法

來源:互聯網
上載者:User

標籤:

總結:

方法一:

#main {

    margin: 0 auto;

    width: 100px;

    height: 100px;

    background-color: #000;

}

/*利用margin的水平方向上auto屬性設定為自動使#main置中顯示,#main需為區塊層級元素而且必須指定寬度,背景是為了展示置中效果*/

 

方法二:

為#main添加一個父元素div

Html:

<div id=”#main-parent”>

    <div id=”#main”></div>

</div>

 

Css:

#main-parent {

    text-align: center;

}

#main {

    display: inline-block;

    width: 100px;

    height: 100px;

    background-color: #000;

}

將其父元素#main-parent設定文本置中屬性text-align:center,再將#main設定為行內塊元素inline-block顯示,也可以實現置中

 

方法三:使用絕對位置

#main {

    width: 100px;

    height: 100px;

    position: absolute;

    top: 0;

    left: 50%;

    margin-left: -50px;

    /*也可以這樣*/

    /*-webkit-transform: translateX(-50%);*/

    /*-moz-transform: translateX(-50%);*/

    /*-ms-transform: translateX(-50%);*/

    /*-o-transform: translateX(-50%);*/

    /*transform: translateX(-50%);*/

}

 

方法四:使用flex布局

給#main添加父元素#main-parent,使其flex布局

#main-parent {

    display: flex;

    width: 1000px;

teight: 500px;

tustify-content: space-around;/*子項目水平置中*/

align-items: center; /*子項目垂直置中*/

}

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.