简体   繁体   中英

Get total width of individual child elements (then half it)

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM