简体   繁体   English

将div(水平和垂直)居中,如果向下滚动则不要留在中间

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

I have a div which is centered horizontally and vertically. 我有一个水平和垂直居中的div。 The problem is that if I scroll down, the div scrolls down too and stays in the center. 问题是,如果我向下滚动,div也会向下滚动并保持在中心位置。 How can I fix that it doesn't scrolls down? 我怎么能解决它不向下滚动?

Right now it it perfectly in the center (I use the margin because of the size of the picture (200px x 200px)). 现在它完全在中心(我使用边距因为图片的大小(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> 

You can wrap the image in an element set to height: 100vh; position: relative; 您可以将图像包装在height: 100vh; position: relative;的元素中height: 100vh; position: relative; height: 100vh; position: relative; so the img will be positioned relatively to an element that matches the viewport (so the 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 stay positioned relative to it. 因此img将相对于与视口匹配的元素定位(因此img将位于视口的中心),当您滚动时,父元素将保留在页面上,图像将保持相对位置它。

 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> 

If you want the same behavior, but want your logo to always stay in the exact same location even as 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's attach to its closest positioned ancestor 位置:绝对意味着它附着在最近的祖先身上

position: fixed attaches to the window itself position:fixed附在窗口本身上

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM