Skip to content

Instantly share code, notes, and snippets.

@elidupuis
Created August 10, 2011 21:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save elidupuis/1138291 to your computer and use it in GitHub Desktop.
Save elidupuis/1138291 to your computer and use it in GitHub Desktop.
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
Copy link

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
Copy link

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