rbuchberger / jekyll_picture_tag

Easy responsive images for Jekyll.
https://rbuchberger.github.io/jekyll_picture_tag/
BSD 3-Clause "New" or "Revised" License
622 stars 106 forks source link

Any support for background? #70

Closed valkjsaaa closed 5 years ago

valkjsaaa commented 8 years ago

It seems that jekyll-asset have support for background image, though the resolution cannot adapt to screen resolution.

lukaszolek commented 7 years ago

+1 Is there any option to use jekyll-picture-tag for "background-image" CSS attribute?

cpury commented 6 years ago

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!

rbuchberger commented 5 years ago

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.