performance boost on fixed background image
Sometimes you need a fixed background-image that, in most cases, covers the background.
The usual approach is to set the CSS-attributes background-attachment: fixed;
and background-size: cover;
To get a performance boost (at least in chrome), you can take the background to a before element.
I got this method from the following blog-post, where you can read it in more detail:
https://fourword.fourkitchens.com/article/fix-scrolling-performance-css-will-change-property
So this is how its done normally:
.fixed-background {
@include clearfix;
border-top: 10px solid rgba(255, 255, 255, .46);
background-color: white;
background: url('/img/bg.jpg') no-repeat center center;
background-attachment: fixed;
background-size: cover;
color: $white;
padding-bottom: 4em;
}
And this gets you loaded faster:
.fixed-background {
@include clearfix;
border-top: 10px solid rgba(255, 255, 255, .46);
color: $white;
padding-bottom: 4em;
overflow: hidden; // added for pseudo-element
position: relative; // added for pseudo-element
// Fixed-position background image
&::before {
content: ' ';
position: fixed; // instead of background-attachment
width: 100%;
height: 100%;
top: 0;
left: 0;
background-color: white;
background: url('/img/bg.jpg') no-repeat center center;
background-size: cover;
will-change: transform; // creates a new paint layer
z-index: -1;
}
}
thats it.
Written by Christoph
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Css
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#