Last active
August 29, 2015 14:06
-
-
Save hellosteadman/1be7ee804bc5e26f2ab1 to your computer and use it in GitHub Desktop.
Make images break out of their containers, responsively
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// I'm using a Ghost theme and I wanted a way for certain images to break out of their container, but | |
// still work responsively. I wrote a JavaScript kludge to do just that. It makes specific images | |
// full-width, then calculates the height the image needs, if it's to retain the same aspect ratio. | |
// We absolutely-position the image to the left, which means all the content that follows will be | |
// out of whack, so we create a div that adds empty (invisible) space between the top of the image | |
// and the next element. We run this every time the browser resizes, and voila... sort of. | |
// I added this JavaScript to the end of my blog theme's <script> tags and it works. That's about | |
// all I can say! | |
// Share and enjoy. | |
$(document).ready( | |
function() { | |
$(window).on('resize', | |
function() { | |
var post = $('.post-content') // Target the main body of a post; | |
var wndWidth = $(window).width(); | |
post.find('img.breakout').each( | |
function() { | |
var self = $(this); | |
var imgWidth = self.width(); | |
var imgHeight = self.height(); | |
var container = self.closest('p') // Assumes all images are in a <p> tag; | |
var newHeight = wndWidth / imgWidth * imgHeight; | |
var afterImg = self.next('.after-img'); | |
if(afterImg.length == 0) { | |
// Creates a 'padding' element so that when we absolutely-position the | |
// image, the page still ends up intact | |
self.after($('<div class="after-img">')); | |
afterImg = self.next('.after-img'); | |
} | |
self.css( | |
{ | |
'left': 0, | |
'position': 'absolute', | |
'width': wndWidth, | |
'margin-left': 0 | |
} | |
).removeClass('img-responsive') // Another plugin I was using was auto-applying this; | |
afterImg.height(newHeight); // Set our post-image padding | |
} | |
); | |
} | |
).trigger('resize') // Do it now! (And when the browser resizes); | |
} | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment