Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS background-size: cover + background-attachment: fixed clipping background images

I have a list of figures containing background images. Something like the following:

<ul>   <li>     <figure style="background-image: url(...);"></figure>   </li>   <li>     <figure style="background-image: url(...);"></figure>   </li>   <li>     <figure style="background-image: url(...);"></figure>   </li> </ul> 

Each of these images has their background-size set to cover and background-attachment set to fixed.

figure {   width: 100%;   height: 100%;   background-size: cover;   background-attachment: fixed; } 

When each of the figures takes up the entire viewport, this works fine, but if there is an offset of any kind the background-image gets clipped.

As far as I can tell this is by design (https://developer.mozilla.org/en-US/docs/Web/CSS/background-size#Values).

I would like the images to either clip vertically or horizontally but not both, and be centred by the size of the figure itself.

I know there are javascript solutions but is there a way to do this using CSS?

Here is a working example: http://codepen.io/Godwin/pen/KepiJ

like image 525
Godwin Avatar asked Feb 14 '14 17:02

Godwin


2 Answers

Unfortunately this is simply an artifact of how fixed positioning works in CSS and there is no way around it in pure CSS - you have to use Javascript.

The reason this happens is due to the combination of background-attachment: fixed and background-size: cover. When you specify background-attachment: fixed it essentially causes the background-image to behave as if it were a position: fixed image, meaning that it's taken out of the page flow and positioning context and becomes relative to the viewport rather than the element it's the background image of.

So whenever you use these properties together, the cover value is being calculated relative to the size of the viewport irrespective of the size of the element itself, which is why it works as expected when the element is the same size as the viewport but is cropped in unexpected ways when the element is smaller than the viewport.

To get around this you basically need to use background-attachment: scroll and bind an event listener to the scroll event in JS that manually updates the background-position relative to how far the window has been scrolled in order to simulate fixed positioning but still calculate background-size: cover relative to the container element rather than the viewport.

like image 120
Ennui Avatar answered Oct 20 '22 11:10

Ennui


There's a jQuery fix for this: http://jsfiddle.net/QN9cH/1/ I know it's not optimal but at least it works :)

$(window).scroll(function() {   var scrolledY = $(window).scrollTop();   $('#container').css('background-position', 'left ' + ((scrolledY)) + 'px'); }); 
like image 32
Nick Noordijk Avatar answered Oct 20 '22 12:10

Nick Noordijk