开发者

Width of first row of floated elements?

Say that I have a bunch of divs floated left, in a grid like fashion. These are in a container with a fixed width.

Now I'd like to know the width of the first row! so that I can compare that width with the fixed width and see i开发者_高级运维f there's a lot of whitespace there, which I would like to minimize.. by setting the container width to the width of the first row of elements.

Now, the difficulty is of that when I float elements there is no concept of first or second row.. Well, I don't really need to know the first row width persé, I just need to know the nr of pixels of white, empty space that is next to the last element to the right side of the container..

See this example: http://i54.tinypic.com/256wdjn.png (don't mind the flashy colors, just for testing)

The right side has too much white space.. I can't just calculate this before hand as the margins, border widths, image widths etc are all dynamic..

Thanks!


Broadly, what you can do is loop through the nested elements and use .offset().top or .position().top. If elements n and n+1 are the first elements to have different top offsets, they must be in different rows.

Then add the width of elements 0 through n (together with their padding, borders, and margins) to get the total width of that row.

(Oh, and don't forget to exit your loop, since you only needed to compute the first row.)


Well, you haven't really shown us your HTML so it's hard to advise very specifically, but the only way I know of to do this is to measure how big one of the grid elements is after it's in the page and then set the container to the closest integral multiple of that so that there is no extra space in the container.

jQuery has very useful methods .width(), .innerWidth() and .outerWidth() for measuring depending upon what exactly you're trying to do.

If the container itself has margins or padding, then you will have to account for that in computing the desired width of the container that leaves the integral amount of space on its interior.


You're overcomplicating it. You really don't need to do any of that. Do you always have 4 images like that? If so you can just use width: 25%; text-align:center; on the elements container.


I'm not sure it works for floated child nodes but you can try to add "display:inline-block" to the container div without width and height specified. this way the container gets as narrow as possible...if that is what you're seeking for.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜