展开一个 div 以填充剩余的宽度

编程入门 行业动态 更新时间:2024-10-27 21:16:53
本文介绍了展开一个 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.

非重复免责声明:

  • 设置 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 { float: left; } .second { background: #ccc; float: none; overflow: hidden; }

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

更多推荐

展开一个 div 以填充剩余的宽度

本文发布于:2023-11-26 12:23:56,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1633921.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:宽度   剩余   div

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!