Center the div (horizontally and vertically) and don't stay in the middle if scrolling down

I have a div that is both horizontally and vertically centered. The problem is if I scroll down the div will also scroll and stay centered. How can I fix it not scrolling down?

Right now it's fine in the center (I'm using margin because of the image size (200px x 200px)). But it stays in the middle when scrolling down.

.logo {
    width: 200px;
    height: 200px;
    position: absolute;
    top: 50%;
    left: 50%;
    margin-top: -100px;
    margin-left: -100px;
    }
      

<image class="logo" src="http://placehold.it/200x200/fc0"></image>
      

Run code


+3


source to share


2 answers


You can wrap the image in an element set to height: 100vh; position: relative;

to be img

positioned relative to the element corresponding to the viewport (so it img

will be in the center of the viewport) and as you scroll, the parent element will stay in place on the page and the image will remain in relation to it.



body {
  margin: 0;
  height: 500vh;
}
div {
  height: 100vh;
  position: relative;
}
.logo {
  width: 200px;
  height: 200px;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%,-50%);
}
      

<div>
  <img class="logo" src="http://kenwheeler.github.io/slick/img/fonz1.png">
</div>
      

Run code


+1


source


If you want the same behavior, but want your logo to always stay in the same place, even if you scroll, change your position from absolute to fixed.

.logo {
    width: 200px;
    height: 200px;

    position: fixed;

    top: 50%;
    left: 50%;
    margin-top: -100px;
    margin-left: -100px;
    }

      



position: absolute means it attaches to the closest located ancestor

position: fixed anchor to the window itself

0


source







All Articles