nelly0213

昨天在知乎上各种看前端的贴,一不小心又学到了个技巧,再次我搬过来和大家分享。

还是同样的问题:

如何让一个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很可爱呢,哈哈哈。

分类:

技术点:

相关文章:

  • 2021-11-20
  • 2022-12-23
  • 2022-12-23
  • 2021-11-30
  • 2021-11-30
  • 2021-09-28
  • 2022-01-24
  • 2021-11-30
猜你喜欢
  • 2021-11-30
  • 2021-11-30
  • 2021-11-30
  • 2021-10-27
  • 2021-11-30
  • 2022-12-23
  • 2021-04-02
相关资源
相似解决方案