CSS background image that can scroll

2019-09-16 14:43发布

I am trying to create a background image that will have a scroll bar to scroll the image down vertically. I like the idea of using width and height percentages because it seems like this method always fits the image to any screen resolution. Unfortunately, the length of the image is rather large and therefore the bottom of the image gets cut off. I have tried various ways to get this working including changing the background-size properties, using overflow-y:scroll and other edits that are not worth mentioning. Here is the code I am working on thus far:

HTML

<!doctype html>
<html>

<head>
<link rel="stylesheet" type="text/css" href="css/style.css">
<meta charset="UTF-8">
</head>

<body>
<div class='image'></div>
</body>

</html>

CSS

@charset "UTF-8";
/* CSS Document */
body { 
    margin:0;
}
.image {
    position:absolute;
    width:100%; 
    height:100%;
    background:black;
    background-image:url(../pictures/testjpg);
    background-size:cover;
    overflow-y: scroll;
}

2条回答
叛逆
2楼-- · 2019-09-16 15:09

A scroll bar moves the viewport so that you can see what's not on the screen. At the above code, if you make your image to expand&contract by giving it relative height (%100 height&width of the screen), there will never be a 'scroll-able' vertical scroll bar because there's nothing to scroll to. It never 'overflows'.

To actually have scroll-able images, you need to give it a width - or in this case- height larger than your viewport.

查看更多
ゆ 、 Hurt°
3楼-- · 2019-09-16 15:10

UPDATE: without height you can't scroll the image top to bottom. but you cant fit this any screen.

body,html {

  margin: 0;
   
}

.image {
  background-image: url("http://www.w3schools.com/howto/img_parallax.jpg");
  background-position:center;
  background-size: 100% 100%;
  
  height:300vh;
  
  }
<body>

   <div class="image">

 </div>
</body>

查看更多
登录 后发表回答