jQuery move floated elements to center

If you want to place floated content to center you should:

  • wrap floated elements;
  • count the the "new width" = sum of widths of children elements;
  • set the width of the wraped parent element as the "new width";

HTML:


<div class="to_center">

	<div class="floated">floated text</div>

	<div class="floated">floated text</div>

	<div class="floated">floated text</div>

</div>

CSS:


.to_center {

margin-left:auto; 

margin-right:auto;

}

.floated {

float:left;

}

jQuery code:


jQuery(function($){

	$('.to_center').each(function(){

		var new_width = 0;

		$(this).children('.floated').each(function(){

			new_width += $(this).width();

		});

		$(this).width(new_width);

	});

});

Note: The sum of widths of your children elements should not exceed the width of the global wrapper or, in the other words, children elements should fit in one line.

Leave a Comment