How to set image in center with position fixed

This question already has an answer here:

  • Center a position:fixed element 11 answers

  • For variable width/height content, you'll want to use a percentage offset with a transform, like this:

    .bgimg {
      top: 50%;
      left: 50%;
      position: fixed;
      opacity:0.09;
      transform: translate(-50%, -50%);
    }
    

    Or, if you know the width and height, you can avoid using a transform and set all the positions to 0 paired with margin: auto; :

    .bgimg {
      width: 400px;
      height: 400px;
      position: fixed;
      top: 0;
      right: 0;
      bottom: 0;
      left: 0;
      margin: auto;
    }
    

    You can see both methods in action, below!

    .bgimg {
      position: fixed;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      opacity: .5;
    }
    
    /* you need to set the width and height on this one, otherwise it stretches it to fill */
    .center-something-without-transform {
      width: 50px;
      height: 50px;
      position: fixed;
      top: 0;
      right: 0;
      bottom: 0;
      left: 0;
      margin: auto;
      background-color: blue;
    }
    <img class="bgimg" src="http://placekitten.com.s3.amazonaws.com/homepage-samples/200/287.jpg" />
    <div class="centered-without-transform"></div>
    链接地址: http://www.djcxy.com/p/75798.html

    上一篇: 滚动条调整页面大小

    下一篇: 如何在位置固定的情况下在中心设置图像