Last active
September 20, 2016 14:07
-
-
Save dylanvalade/7088132 to your computer and use it in GitHub Desktop.
Center child element vertically within parent with jQuery
This file contains 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
// child: jquery object e.g $(".active .slide-caption") | |
// parent: jquery object e.g $(".active.slide") | |
// property (string): CSS property to change depending on your CSS positioning e.g. "top", "margin-top" or "bottom" | |
function centerVertical(child, parent, property) { | |
var parentHeight = parent.height(), | |
childHeight = child.height(); | |
// Handle edge cases with padding or margins affecting child.height() calculation | |
if (child.find("h1").length) { | |
childHeight = child.find("h1").height(); | |
} | |
// Position the child with an inline style | |
child.css(property, (parentHeight - childHeight) / 2); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment