当前位置: 动力学知识库 > 问答 > 编程问答 >

css - background-attachment:scroll and background-size:cover not working

问题描述:

I have a background image that I want to be fixed on larger screens and scroll on smaller devices.

This works great...

#main_page {

height: 100%;

min-height: 100%;

background-image:url('url');

background-position: 50% 50%;

background-size: cover;

-webkit-background-size: cover;

-moz-background-size: cover;

-o-background-size: cover;

background-repeat: no-repeat;

background-attachment: fixed;

}

however I want to be able to use...

@media (max-width: 991px) {

#main_page { background-attachment:scroll; }

}

Using the background-attachment:scroll seems to kill background-size:cover and show it at it's full size (even bigger I think). When I test background-attachment: scroll; in the first set of CSS it does the same thing.

This exact thing seems to work on this site.... http://www.julytalk.com/ what am I missing?

网友答案:

I think I see what you mean. In the event that #main_page extends below the bottom of the viewport (I saw no problems here when it did not), the background image seems to inexplicably jump in size as soon as the media query breakpoint is reached and the background-attachment changes.

There's actually a good reason for this, and it relates primarily to your use of background-size: cover. While the style for #main_page is background-attachment: fixed, the area that this background needs to cover is only the size of the viewport, since the background never changes position relative to it.

However, once you cross that media query breakpoint and the style for #main_page changes to background-attachment: scroll, this area suddenly changes. Since the background now moves relative to the viewport, any part of #main_page that extends below the viewport needs to be covered as well. To account for this new area to cover, the background image instantly scales, resulting in this jump in size. (Exhibited in this JSFiddle.)

The site you linked to uses effectively similar styles to you, but ensures that their counterpart of #main_page never extends more than 100% of the viewport. For example, this JSFiddle uses your CSS to achieve a similar effect to them (no image size jump), since #main_page doesn't contain any content that would force it to exceed 100% of the viewport height.

Hope this helps! Let me know if you have any questions.

分享给朋友:
您可能感兴趣的文章:
随机阅读: