1

Dynamic size of the background image to fit the window

 2 years ago
source link: https://www.codesd.com/item/dynamic-size-of-the-background-image-to-fit-the-window.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Dynamic size of the background image to fit the window

advertisements

I have what I thought would be a common issue diagnosed online but nothing I am seeing seems to be working as I expect for some reason. I basically have a web site that has several backgrounds stacked on each other. The idea is that buttons will scroll the background up to the next - (critical point) where each background fits the viewable area of the browser exactly, something like:

[Edit] My problem is with getting the background images/div to fit the size of the browser no matter what size it is. In this example the background fits in the browser nicely, but when I resize (as expected as I have set the background height) you can start to see the next background underneath:

I want the first background to fill the viewable browser window. Only when I click the relevent button will the next background become visible - and will itself fill the viewable browser space.

I am at work at the moment and dont have code ro hand to show exactly what I have tried but feel free to put any suggestions this way as I may have just missed a small detail from other findings I have tried.


The vh unit can be used to set the height of the backgrounds. In the following example however, I have used it to set the height of divs, and let the background images have auto width, 100% height:

body {
  margin: 0;
}

#menu {
  position: fixed;
  left: .5em;
  top: .5em;
  right: .5em;
  padding: .5em;
  background-color: rgba(255, 255, 255, .7)
}

.item {
  height: 100vh;
  background-size: auto 100%;
  background-position: center center;
}

#item-1 {
  background-image: url(https://dummyimage.com/200x100/FC0/FFF&text=Background+Image);
}

#item-2 {
  background-image: url(https://dummyimage.com/200x100/F0C/FFF&text=Background+Image);
}

#item-3 {
  background-image: url(https://dummyimage.com/200x100/0CF/FFF&text=Background+Image);
}
<div id="menu">
  <a href="#item-1">Item 1</a>
  <a href="#item-2">Item 2</a>
  <a href="#item-3">Item 3</a>
</div>
<div id="item-1" class="item"></div>
<div id="item-2" class="item"></div>
<div id="item-3" class="item"></div>

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK