css中圖片使用絕對位置實現置中效果[第二篇]

來源:互聯網
上載者:User

標籤:技巧   round   containe   color   分享   tom   position   height   relative   

昨天在知乎上各種看前端的貼,一不小心又學到了個技巧,再次我搬過來和大家分享。

還是同樣的問題:

如何讓一個div在父元素中置中?

在上一篇裡我們用到了絕對位置position:absolute;

再結合margin的負值實現了置中的效果。

第二種解決辦法

在此我們來看下新的方法:

  html:

    <div class="container">

      <div class="box"></div>

    </div>

  css:

    .container{

      width:300px;

      height:300px;

      position:relative;

    }

    .box{

      width:50px;

      height:50px;

      margin:auto;

      position:absolute;

      top:0;

      bottom:0;

      left:0;

      right:0;

    }

這樣就實現啦!(●‘?‘●)

原理

之前什麼margin都不用算啦!這個方法直接搞定置中問題。

我們給box設定了絕對位置,上下左右都是0;

這時box就懵逼了,到底往哪走???

算了,我還是待在中間吧QAQ

仔細想想還突然覺得這個box很可愛呢,哈哈哈。

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.