我想要一个两列的 div 布局,其中每一个都可以有可变的宽度,例如
I want a two-column div layout, where each one can have variable width e.g.
div { float: left; } .second { background: #ccc; } <div>Tree</div> <div class="second">View</div>我希望在 'tree' div 填满所需空间后,'view' div 扩展到可用的整个宽度.
I want the 'view' div to expand to the whole width available after 'tree' div has filled needed space.
目前,我的视图"div 被调整为它包含的内容如果两个div都占据整个高度也不错.
Currently, my 'view' div is resized to content it contains It will also be good if both divs take up the whole height.
非重复免责声明:
- 设置 float:left 时将 div 扩展到最大宽度因为左边的宽度是固定的.
- 帮助 div - 使 div 适合剩余宽度因为我需要两列都向左对齐
- Expand div to max width when float:left is set because there the left one has a fixed width.
- Help with div - make div fit the remaining width because I need two columns both aligned to left
这个问题的解决方案其实很简单,但不是所有显而易见的.你必须触发一个叫做块格式化上下文"的东西.(BFC),它以特定方式与浮点数交互.
The solution to this is actually very easy, but not at all obvious. You have to trigger something called a "block formatting context" (BFC), which interacts with floats in a specific way.
只需取第二个 div,移除浮点数,然后给它 overflow:hidden 代替.除了可见之外的任何溢出值都会使其设置的块成为 BFC.BFC 不允许后代浮点数逃脱它们,也不允许兄弟/祖先浮点数侵入它们.这里的实际效果是浮动的 div 会做它的事情,然后第二个 div 将是一个普通的块,占据所有可用的宽度除了被浮动占据的宽度.
Just take that second div, remove the float, and give it overflow:hidden instead. Any overflow value other than visible makes the block it's set on become a BFC. BFCs don't allow descendant floats to escape them, nor do they allow sibling/ancestor floats to intrude into them. The net effect here is that the floated div will do its thing, then the second div will be an ordinary block, taking up all available width except that occupied by the float.
这应该适用于所有当前浏览器,尽管您可能需要在 IE6 和 7 中触发 hasLayout.我不记得了.
This should work across all current browsers, though you may have to trigger hasLayout in IE6 and 7. I can't recall.
演示:
- 固定左侧:jsfiddle/A8zLY/5/
- 固定右侧:jsfiddle/A8zLY/2/
更多推荐
展开一个 div 以填充剩余的宽度
发布评论