Created
February 12, 2016 14:01
-
-
Save adammacias/14f5ac3c128c77106c65 to your computer and use it in GitHub Desktop.
Fake background-position cover with javascript by absolute positioning by an image inside its parent.
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
| /* Fake background-position cover with javascript by absolute positioning | |
| * an image inside its parent. | |
| */ | |
| function coverImage(image) { | |
| var $image = $(image); | |
| var $parent = $(image).parent(); | |
| $parent.imagesLoaded(function () { | |
| var width = $image.width(); | |
| var height = $image.height(); | |
| var parent_width = $parent.outerWidth(); | |
| var parent_height = $parent.outerHeight(); | |
| var image_ratio = width/height; | |
| var parent_ratio = parent_width/parent_height; | |
| image.css({ position: 'absolute' }); | |
| if (image_ratio > parent_ratio) { | |
| // Case: fit vertically and center horizontally | |
| image.css({ | |
| height: parent_height, | |
| width: 'auto', | |
| top: 0 | |
| }); | |
| // recalculate since we change the height | |
| width = $image.width(); | |
| image.css({ | |
| left: parent_width/2 - width/2 | |
| }); | |
| } else { | |
| // Case: fit horizontally and center vertically | |
| image.css({ | |
| height: 'auto', | |
| width: parent_width, | |
| top: 0 | |
| }); | |
| // recalculate since we change the height | |
| height = $image.height(); | |
| image.css({ | |
| top: parent_height/2 - height/2 | |
| }); | |
| } | |
| }); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment