利用CSS實現div水平垂直置中

來源:互聯網
上載者:User
實現置中的方案有很多,這裡介紹下純CSS使用absolute配合margin的方案。

1. p寬高固定

width: 400px;height: 200px;position: absolute;top: 50%;left: 50%;margin-top: -100px;margin-left: -200px;

margin-top為-(height / 2),margin-left為-(width / 2)。當然也可以不用margin,即top為calc(100% - height) / 2,left為calc(100% - width) / 2,但是建議可以不用calc()就不要用。

2. p寬高不固定

width: 50%;height: 50%;position: absolute;top: 0;right: 0;bottom: 0;left: 0;margin: auto;

注意,這適用於寬高需指定的情況,比如使用百分比或者用js動態修改,不然可能被當成100%處理。

也可以不用margin用translate(),如下:

width: 50%;height: 50%;position: absolute;top: 50%;left: 50%;transform: translateX(-50%) translateY(-50%);

3. CSS3不定寬高水平垂直置中

justify-content: center; /* 子項目水平置中 */align-items: center;     /* 子項目垂直置中 */display: -webkit-flex;

在父級元素上添加,即可實現子項目水平垂直置中。

聯繫我們

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