关于position:fixed;的居中问题

转自:https://www.cnblogs.com/zywaf/p/7217102.html?utm_source=itdadao&utm_medium=referral

通常情况下,我们通过操作margin来控制元素居中,代码如下:

#name{
    maigin:0px auto;
}

但当我们把position设置为fixed时,例如:

#id{
   position:fixed;
   margin:0px auto;
}

以上代码中的margin:0px auto;会出现失效问题,盒子并未居中。这是因为fixed会导致盒子脱离正常文档流。
解决方法非常简单,只要应用如下代码即可:

#name{
    position:fixed;
    margin:0px auto;
    right:0px;
    left:0px;
}

若希望上下也可以居中,可采用如下代码

#name{
    position:fixed;
    margin:auto;
    left:0;
    right:0;
    top:0;
    bottom:0;
}

万能居中法(未知大小呦):

#name{
      position:fixed;
      left:50%;
      top:50%;
      transform:translate(-50%,-50%);
      z-index:1000;      
}

猜你喜欢

转载自blog.csdn.net/qq285679784/article/details/85251347