0

I am trying to center image with position fixed in CSS. The code I tried

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

Refer to https://www.w3schools.com/code/tryit.asp?filename=FJZQPD9BZUBG

1 Answers1

0

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>
Jonathan Bowman
  • 1,606
  • 1
  • 12
  • 17