【问题标题】:How to set image in center with position fixed [duplicate]如何将图像设置在中心位置固定[重复]
【发布时间】:2018-03-10 11:56:11
【问题描述】:

我正在尝试以 CSS 中固定的位置居中图像。我试过的代码

<style>
.bgimg {
    top: 50%;
    left: 50%;
    position: fixed;
    opacity:0.09;
    marging: auto;
}
</style>

参考https://www.w3schools.com/code/tryit.asp?filename=FJZQPD9BZUBG

【问题讨论】:

    标签: css


    【解决方案1】:

    对于可变宽度/高度的内容,您需要在变换中使用百分比偏移量,如下所示:

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

    或者,如果您知道宽度和高度,则可以避免使用变换并将所有位置设置为 0margin: auto; 配对:

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

    您可以在下面看到这两种方法的实际效果!

    .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>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-04-25
      • 1970-01-01
      • 1970-01-01
      • 2014-10-26
      • 1970-01-01
      • 1970-01-01
      • 2021-08-08
      • 1970-01-01
      相关资源
      最近更新 更多