Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
jquery plugin to set the width of an element to the sum of it's children's width
$.fn.matchWidth = function(){
// Prepare
var $this = $(this);
// Action
$this.width(function(){
var w = 0;
$(this).children().each(function(){
w += $(this).outerWidth(true);
});
return w;
});
// Chain
return $this;
};
@rystraum

This comment has been minimized.

Copy link

@rystraum rystraum commented May 7, 2014

Technically, this is correct, but in practice it's more common to set the elements width based on the largest child's width. In that case, just replace the action part into:

$this.width(function(){
  var w = 0;
  $this.children().each(function(){
    var outerwidth = $(this).outerWidth(true);
    if(w < outerwidth) {
      w = outerwidth;
    }
  });
  return w;
});
@rystraum

This comment has been minimized.

Copy link

@rystraum rystraum commented May 7, 2014

Thanks for the gist! :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.