CSS background and skin fixed

I want to set a fixed background image that also spans the div, but for some reason when I add the fixed in CSS, the image is stretched outside the div.

These are two examples, one with fixed (wrong dimensions) and the other with correct dimensions, but it's not fixed (it scrolls the 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>
      

Run codeHide result


How can you use both of these properties to work together? Are they incompatible?

EDIT: For some reason, the fixed property refers to the viewport, not the element itself . The higher the screen, the larger the image gets. Is there a twist?

+3


source to share


2 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 with https://developer.mozilla.org/en-US/docs/Web/CSS/position

Leave no space for the item. Instead, position it at the specified position relative to the screen viewer and do not move it when scrolling. When printing, place it in this fixed position on each page.



So what it does is your "out of the div" background image and its size relative to the viewport itself. This is why it is "scaling" and "clipping" your background image.

You can work around this issue with JavaScript or jQuery. Here is a snippet of 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>
      

Run codeHide result


+4


source


Try the following:



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

      

-1


source







All Articles