本文介绍了浮动父div增长到浮动子div的假定宽度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个浮动的父元素和一个也浮动的子元素,还有一些内容使子元素具有某些尺寸,如下所示:

I have a parent element that floats and a child element that also floats, plus some content to give the child element some dimensions, as follows:

<div id="parent">
  <div id="child">
    WWWWWWW WWWWWWW WWWWWWW
  </div>
</div>

孩子的宽度受 width 的限制和最小宽度

The child has its width restricted through width and min-width:

#parent {
  width: auto;
  float: left;
}

#child {
  width: 16%;
  min-width: 150px;
  float: left;
}

我希望发生的是父div的宽度与子div,而不是100%,因为它是浮动的。

What I would expect to happen is that the parent div has the same width as the child div, and not 100%, since it's floated.

虽然不会发生什么。父div之间有一些宽度。似乎发生的事情是,如果父div的宽度不受限制,则其父div的宽度将等于子div 的宽度,即子div从其文本中获得的宽度会延伸到

What happens though is neither. The parent div has some width inbetween. What seems to happen is that the parent div has the width that the child div would have if it wasn't width-restricted, i.e. the width that the child would get from the text in it stretching over just one line instead of wrapping.

但是,孩子被设置得更窄了,为什么父母也不会缩小呢?
而我该怎么做呢?

However the child is set to be narrower so why does the parent not shrink to that too?And how can I get it to do that?

在。您应该看到黑色父框没有延伸到灰色背景的整个宽度,但也比红色子框宽。

See a full example on http://jsbin.com/wipafizocu/edit?html,css,output that uses some colouring to show the divs. You should see that the black parent box does not extend to the full width of the grey background but is also wider than the red child box.

推荐答案

从中:

父级和子级宽度之间存在循环依赖关系。由于父级具有 width:auto 的宽度,因此其宽度是根据,导致您观察到的行为,即

There's a circular dependency between the parent and child widths. As the parent has width: auto, its width is calculated based on the shrink-to-fit algorithm described here, resulting in the behavior you observe, namely,

然后,将子级的宽度计算为父级使用的宽度的百分比。如果父级再次收缩以适合孩子,则子级将不再是父级宽度的16%,因此必须重新计算其宽度。您可以看到行进方向。

The child's width is then calculated as a percentage of the used width of the parent. If the parent were to shrink again to fit the child, then the child would no longer be 16% of the parent width, and its width would have to be recalculated. You can see where this is going.

因此,实现同意不要重复计算两个元素的宽度。请注意,指定最小宽度不会影响任何这种行为。

So implementations agree not to calculate the width of either element more than once. Note that specifying a min-width does not influence any of this behavior.

这里没有很多解决方案;由于您依靠的是不确定的行为,因此即使flexbox也无济于事。您可能需要重新考虑布局。

There isn't much of a solution here; not even flexbox will help, since you're relying on undefined behavior. You may have to rethink your layout.

这篇关于浮动父div增长到浮动子div的假定宽度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-31 02:18