Answer the question
In order to leave comments, you need to log in
How to align blocks by width with jQurey?
Good afternoon!
A long time ago, a question was asked here about aligning blogs in width.
The following option has been proposed:
<style>
div.item {width: 250px; height: 150px; background: red; float: left;}
</style>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript">
$(function ()
{
changeMargin();
});
$(window).resize(function()
{
changeMargin();
});
function changeMargin()
{
var container_width = $('div.container').width();
var item_width = $('div.item').width();
var items_count = Math.floor(container_width / item_width);
var items_width = item_width * items_count;
var difference = container_width - items_width;
var margin = difference / (items_count - 1);
$('div.item').each(function(index)
{
if (index > 0 && index % items_count != 0)
$(this).css('margin-left', margin+'px');
else
$(this).css('margin-left', '0px');
});
}
</script>
<div class="container">
<div class="item">1</div>
<div class="item">2</div>
<div class="item">3</div>
<div class="item">4</div>
<div class="item">5</div>
<div class="item">6</div>
<div class="item">7</div>
<div class="item">8</div>
</div>
Answer the question
In order to leave comments, you need to log in
For lining up blocks (including on several lines) and aligning the width (as well as height) of the container, it is already common to use flex , and not plugins with floating (oh, horror) elements.
As to a question on a script.
Assigned. Only the value '0' - in the same place the check is for compliance with the number in the line.
if (index > 0 && index % items_count != 0)
$(this).css('margin-left', margin+'px');
else
$(this).css('margin-left', '0px');
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question