简体   繁体   English

将父 div 包裹在浮动元素周围

[英]Wrapping a parent div around floated elements

I'm trying to get a div to wrap around a dynamic number of child elements and I'd like to do this without setting a value for the width of the parent.我试图让一个 div 包围动态数量的子元素,我想在不设置父元素宽度值的情况下执行此操作。

I've got the content wrapping by floating both the child and parent elements, my problem is when the child elements wrap onto the next line there's free space left over on the right side and I'd like the parent to wrap "tightly".我通过浮动子元素和父元素获得了内容换行,我的问题是当子元素换行到下一行时,右侧有剩余空间,我希望父元素“紧紧地”换行。

I've set up a demo here: http://jsfiddle.net/UMgct/4/我在这里设置了一个演示: http://jsfiddle.net/UMgct/4/

#parent shows the current behaviour, I'd like it to behave like #parent2 and #parent3, but without explicitly setting the width. #parent 显示当前行为,我希望它表现得像#parent2 和#parent3,但没有明确设置宽度。 I can see why the behaviour for #parent is correct, I just can't see any way of getting the behaviour I would like.我明白为什么 #parent 的行为是正确的,我只是看不到任何获得我想要的行为的方法。

Any ideas would be greatly appreciated任何想法将不胜感激

First off, you should change 'parent' and 'child' to be classes instead of IDs.首先,您应该将“parent”和“child”更改为类而不是 ID。 IDs are meant to be unique identifiers, while classes can be used as many times as you want. ID 是唯一标识符,而类可以根据需要多次使用。

With that said, you can achieve what you want with JQuery (assuming the IDs are now changed to classes):话虽如此,您可以使用 JQuery 实现您想要的(假设 ID 现在已更改为类):

$(document).ready(function() {
    var numPerLine = parseInt($(window).width() / $('.parent > .child').outerWidth(true));
    $('.parent').width($('.parent > .child').outerWidth(true) * numPerLine);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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