Reputation: 1665
I have a div which contains multiple children. I'm planning on using a horizontal layout so I need to set a width on the parent div for the layout to run from left to right. Rather than all the items in a single row I want 2 rows, so once I have the total width I'll need to divide it by 2 so the items wrap onto another line.
The number of children will change, so a CSS value isn't appropriate in this situation.
The mark-up will look a bit like this:
<div id="container">
<figure>1</figure>
<figure>2</figure>
<figure>4</figure>
<figure>5</figure>
<figure>6</figure>
</div>
Really appreciate it if someone can help me with this. I've managed to get the dimensions of a single element before but I can't see to do it for a group.
Thanks in advance, Steve
Upvotes: 0
Views: 111
Reputation: 1286
Please refer to this fiddle: https://jsfiddle.net/m6k1jamd/
What has to be done to acheive this is:
- On page load get a predefined width for the figure (set in css)
- Get the number of girues within the container
- Work out how many figures to show per row (you want 2 rows).
- Force 2 rows by using Math.ceil()
- Determine how wide each row is by calculating the number of figures per row * figure width.
- Set the containers width to the calculated row width.
Javascript from above logic
$(document).ready(function(){
//Get the figures width
var figure_width = $("#container figure").css("width").replace("px", "");
//Get num figures
var num_figures = $("#container figure").length;
//Work out how manay figures per row
var num_row_figures = Math.ceil(num_figures / 2);
//Get the total width
var row_width = figure_width * num_row_figures;
//Set container width to half the total
$("#container").width(row_width);
});
Hope this helps!
Josh
Upvotes: 1