css div上下左右居中

相信大家都会遇到这样的问题,要求一个块上下左右居中,在这里我总结了几个好用的方法

1.已知要居中的块width height

 假设  content 要在f里上下左右居中

<div class="f"><div class="content"></div></div>

<style>

.f{

     800px; 

    height: 800px;

  position:relative;

}

.content{

  500px;

     height:500px;

  position:absolute;

  top:50%;

  left:50%;

  margin-top:-250px;

  margin-left:-250px;

}

</style>

这样子相对于父上下左右居中,,这是常见的一种解决方案原理就是子相对于父绝对定位,先下移左移50%,此时子的左上脚在父的中心,再回移自己的宽高一半,即可居中。

2.已知宽,不知高,(确定高度的也可用)

.f{

     800px; 

    height: 800px;

}

.content{

  500px;

     height:auto;

  margin:auto auto

}

这种方法明显比第一种简化很多。

但前两种方法都是在已知宽度的情况下才行,,应用场景不够全面。下面说一种 终极方法,我自己也在很多场景下应用到了

3.不知 width height

.toast {

    border-radius: 5px;

    position: fixed;

    top: 50%;

    left: 50%;

    -webkit-transform: translate(-50%, -50%);

    -ms-transform: translate(-50%,-50%);

    -moz-transform: translate(-50%,-50%);

    -o-transform: translate(-50%,-50%);

    transform: translate(-50%, -50%);

    z-index: 12;

    background: rgba(0,0,0,0.7);

    color: #fff;

    padding: 5px 10px;

    line-height: 20px;

    font-size: 16px;

    text-align: center;

}

这是我写的toast提示的样式,在未知宽高的情况下相对屏幕上下左右居中。

原理与第一个相似,都是先相对父级移50%;再相对自己移回-50%;

原文地址:https://www.cnblogs.com/manman04/p/5624237.html