如何在中心位置固定图像

时间:2017-09-28 16:37:22

标签: css

我试图将图像置于CSS中固定的位置。我试过的代码

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

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

1 个答案:

答案 0 :(得分:0)

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

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

您可以在下方看到两种方法!

&#13;
&#13;
.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;
}
&#13;
<img class="bgimg" src="http://placekitten.com.s3.amazonaws.com/homepage-samples/200/287.jpg" />
<div class="centered-without-transform"></div>
&#13;
&#13;
&#13;