Created
September 7, 2012 04:46
-
-
Save nathanielks/3663253 to your computer and use it in GitHub Desktop.
jQuery Element Inline Distributor
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
Description: | |
I wrote this so that I could evenly distribute elements in a line. Here's an example that may explain better than words: http://cl.ly/JHnp, http://jsfiddle.net/nathanielks/pvGcz/4/. What it does it take the parent element and scans it for specific child elements. It then calculates the various widths and adds a left margin accordingly. The reason each element is given a display: block and float:left is because of a weird bug with display: inline. The script requires the elements to displayed inline initially, but because inline elements have a few extra pixels around them, the elements aren't all contained, even though the math is right. Really weird. Anyway, here's how you use it. | |
Usage: | |
$('#parent').distributeElements(); | |
Here's the demo: http://jsfiddle.net/nathanielks/pvGcz/4/ |
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
/** | |
* jQuery distribute elements evenly in a line | |
* | |
* @author Nathaniel Schweinberg | |
* @link http://nathanielks.me | |
* @since Version 1.0 | |
* @notes Works great on li elements that you want to fill up an entire line | |
* | |
*/ | |
(function($) | |
{ | |
$.fn.distributeElements = function() { | |
var $parent = $(this), | |
parentWidth = $parent.outerWidth(), | |
offset = 0, | |
numOfChildren = 0, | |
firstChildWidth = 0, | |
childrenTotalWidth = 0; | |
$.each( $parent.children(), function(){ | |
if ( $(this).is(':first-child') ){ | |
firstChildWidth = $(this).outerWidth(); | |
} | |
$this.css('display', 'inline'); | |
childrenTotalWidth += $(this).outerWidth(); | |
numOfChildren++; | |
}); | |
offset = ( parentWidth - childrenTotalWidth ) / ( numOfChildren - 1 ); | |
$.each( $parent.children(), function(){ | |
if ( ! $(this).is(':first-child') ){ | |
$(this).css({ marginLeft: offset + 'px' }); | |
} | |
$(this).css({ | |
display: 'block', | |
float: 'left' | |
}); | |
}); | |
return this; | |
}; | |
})(jQuery); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment