在下面的jsFiddle中,当有两行时,容器div的宽度为100%,而当只有一行时,容器div的宽度小于100%(即包装子项)。
我希望容器div position: relative;
top: 25%;
尽可能地紧紧围绕孩子。我怎样才能做到这一点?
答案 0 :(得分:0)
有趣的问题。您当然希望浮动容器div不超过子容器的宽度(因为它只有一行)。
如果您知道每行中的项目数,那么使用行 div包装项目似乎有效:
<div class="photo_stream_wrapper">
<div> <!-- "row" div -->
<div class="photo"></div>
<div class="photo"></div>
<div class="photo"></div>
</div>
<div> <!-- "row" div -->
<div class="photo"></div>
</div>
</div>
答案 1 :(得分:0)
I had a very similar problem, which can be referenced in my post:
In my case I have something along the lines of this:
<div class="centered">
<div class="container">
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
</div>
</div>
It looks like jQuery is the answer. In order to "dynamically" set the width of the containing div, we need to calculate the width on a screen resize event via jQuery. We can use the width of the window and the width of the children to calculate the width of the inner container.
Here is the fiddle:
var resizeContainerDiv = function() {
var screenWidth = $(window).width();
var childWidth = $(".child").outerWidth();
var innerContainerWidth = Math.floor(screenWidth / childWidth) * childWidth;
$('.container').css('width', innerContainerWidth);
}
$(window).on("load", resizeContainerDiv);
$(window).on("resize", resizeContainerDiv).resize();
.centered {
text-align: center;
}
.container {
background: red;
padding: 10px;
display: inline-block;
}
.child {
width: 100px;
height: 100px;
float: left;
}
.child:nth-child(even) {
background: green;
}
.child:nth-child(odd) {
background: blue;
}
<div class="centered">
<div class="container">
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
</div>
</div>