利用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;

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

相關文章

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.