Closed valkjsaaa closed 5 years ago
+1 Is there any option to use jekyll-picture-tag for "background-image" CSS attribute?
I got this to work with a little hack:
Have an invisible image. That makes sure a) the resized images are generated when the site is built and b) the browser picks the right image based on browser size.
Then we can use jquery to set the background-image:
<header class="masthead"> <!-- The div that we want to add the background to -->
{% picture {{ page.background }} class="d-none" %} <!-- Make sure this is set to display: none -->
<script>
// Set background image responsively
$(document).ready(function() {
var updateHeaderBackground = function() {
var $img = $('header img.d-none');
if (!$img.length) {
console.error('Could not resize header image');
}
var src = $img[0].currentSrc;
$('header').css('background-image', 'url(' + src + ')');
};
updateHeaderBackground();
});
</script>
...
</header>
You could also call updateHeaderBackground()
after every window resize etc.
Hope that helps!
The thing about doing responsive CSS background images is that they're pretty integrated with your site's HTML and/or CSS. It's not like a <picture>
element, which is mostly self contained. This makes it harder to just spit out a block of useful code, and will require a lot of configuration from the user. It's doable, but I don't think it's within the scope of this plugin.
I'd advise you to use the direct_url
markup format, which just gives you a resized image and a URL to do whatever you like with. Something like this:
---
---
/* some_file.css */
/* Don't forget the yaml front matter block, or jekyll won't parse the picture tag. */
#body {
background-image: url("{% picture direct-url background.jpg %}");
}
# _data/picture.yml
markup_presets:
direct-url:
output_format: direct_url
fallback_width: 1200
Sorry I can't be more helpful. If someone wants to take a crack at writing a proper output format for this, pull requests are welcome, but I won't be doing it.
It seems that jekyll-asset have support for background image, though the resolution cannot adapt to screen resolution.