展开一个 div 以填充剩余的宽度 [英] Expand a div to fill the remaining width

查看:27
本文介绍了展开一个 div 以填充剩余的宽度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一个两列的 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.

非重复免责声明:

  • 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.

演示:

div {
  float: left;
}

.second {
  background: #ccc;
  float: none;
  overflow: hidden;
}

<div>Tree</div>
<div class="second">View</div>

这篇关于展开一个 div 以填充剩余的宽度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆