Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS background fixed and cover

Tags:

css

I want to set a fixed background image that also covers the div but for some reason when I add fixed to the CSS, the image gets stretched way beyond the boundaries of the div.

These are 2 examples, one with fixed (incorrect dimensions) and the other with the correct dimensions but it's not fixed (it scrolls with page)

#incorrect{
  min-height:100px;
  background: url('http://034.83e.myftpupload.com/wp-content/uploads/2015/04/entete_image.png') no-repeat fixed center/cover;
  }

#correct{
  min-height:100px;
  background: url('http://034.83e.myftpupload.com/wp-content/uploads/2015/04/entete_image.png') no-repeat center/cover;
  }
<div id="incorrect"></div>

<br>

<div id="correct"></div>

How do you get both of these properties to work together? Are they incompatible?

EDIT: for some reason,the fixed property is relative to the viewport and not to the element itself The higher the screen, the bigger the image gets. Is there a turnaround?

like image 525
BassMHL Avatar asked May 17 '26 16:05

BassMHL


1 Answers

What you are trying to do is not possible with pure CSS.

When you use background-attachment: fixed; it makes the image act the same as position:fixed.

position:fixed explained via https://developer.mozilla.org/en-US/docs/Web/CSS/position

Do not leave space for the element. Instead, position it at a specified position relative to the screen's viewport and don't move it when scrolled. When printing, position it at that fixed position on every page.

So what it's doing is taking your background image "out of the div" and sizing it relative to the viewport itself. This is why it is "zooming" and "clipping" your background image.

You can work around this issue with JavaScript or jQuery. Here is a snippet with your code used as an example:

$(window).scroll(function() {
  var scrolledY = $(window).scrollTop();
  $('#incorrect').css('background-position', 'left ' + ((scrolledY)) + 'px');
});
#incorrect{
  min-height:100px;
  background: url('http://034.83e.myftpupload.com/wp-content/uploads/2015/04/entete_image.png') no-repeat scroll center/cover;
  }

#correct{
  min-height:100px;
  background: url('http://034.83e.myftpupload.com/wp-content/uploads/2015/04/entete_image.png') no-repeat center/cover;
  }

div{margin-bottom:200px;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="incorrect"></div>

<br>

<div id="correct"></div>
like image 198
xengravity Avatar answered May 19 '26 11:05

xengravity



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!