简体   繁体   English

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

[英]Expand a div to fill the remaining width

I want a two-column div layout, where each one can have variable width eg我想要一个两列的 div 布局,其中每个列都可以有可变宽度,例如

 div { float: left; }.second { background: #ccc; }
 <div>Tree</div> <div class="second">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.目前,我的“视图”div 已调整为它包含的内容如果两个 div 都占据整个高度也很好。


Not duplicate disclaimer:不重复免责声明:

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.你必须触发一个叫做“块格式上下文”(BFC)的东西,它以特定的方式与浮点数交互。

Just take that second div, remove the float, and give it overflow:hidden instead.只需取出第二个 div,移除浮动,然后将其设置为overflow:hidden Any overflow value other than visible makes the block it's set on become a BFC.除了可见之外的任何溢出值都会使其设置的块成为 BFC。 BFCs don't allow descendant floats to escape them, nor do they allow sibling/ancestor floats to intrude into them. BFC 不允许后代浮点数逃脱它们,也不允许兄弟/祖先浮点数侵入它们。 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 .这里的实际效果是浮动的 div 会做它的事情,然后第二个 div 将是一个普通的块,占用所有可用的宽度,除了被 float 占用的宽度。

This should work across all current browsers, though you may have to trigger hasLayout in IE6 and 7. I can't recall.这应该适用于所有当前浏览器,尽管您可能必须在 IE6 和 7 中触发 hasLayout。我不记得了。

Demos:演示:

 div { float: left; } .second { background: #ccc; float: none; overflow: hidden; }
 <div>Tree</div> <div class="second">View</div>

I just discovered the magic of flex boxes (display: flex).我刚刚发现了弹性盒的神奇之处(display: flex)。 Try this:尝试这个:

<style>
  #box {
    display: flex;
  }
  #b {
    flex-grow: 100;
    border: 1px solid green;
  }
</style>
<div id='box'>
 <div id='a'>Tree</div>
 <div id='b'>View</div>
</div>

Flex boxes give me the control I've wished css had for 15 years. Flex 框给了我 15 年来一直希望 css 拥有的控制权。 Its finally here!它终于来了! More info: https://css-tricks.com/snippets/css/a-guide-to-flexbox/更多信息: https : //css-tricks.com/snippets/css/a-guide-to-flexbox/

Use the CSS Flexbox flex-grow property to achieve this.使用CSS Flexbox flex-grow属性来实现这一点。

 html, body { height: 100%; } body { display: flex; } .second { flex-grow: 1; }
 <div style="background: #bef;">Tree</div> <div class="second" style="background: #ff9;">View</div>

This would be a good example of something that's trivial to do with tables and hard (if not impossible, at least in a cross-browser sense) to do with CSS.这将是一个很好的例子,它与表格无关,而与 CSS 很难(如果不是不可能,至少在跨浏览器的意义上)。

If both the columns were fixed width, this would be easy.如果两列都是固定宽度,这将很容易。

If one of the columns was fixed width, this would be slightly harder but entirely doable.如果其中一列是固定宽度,这会稍微困难一些,但完全可行。

With both columns variable width, IMHO you need to just use a two-column table.对于两列可变宽度,恕我直言,您只需要使用两列表格即可。

Check this solution out检查这个解决方案

 .container { width: 100%; height: 200px; background-color: green; } .sidebar { float: left; width: 200px; height: 200px; background-color: yellow; } .content { background-color: red; height: 200px; width: auto; margin-left: 200px; } .item { width: 25%; background-color: blue; float: left; color: white; } .clearfix { clear: both; }
 <div class="container"> <div class="clearfix"></div> <div class="sidebar">width: 200px</div> <div class="content"> <div class="item">25%</div> <div class="item">25%</div> <div class="item">25%</div> <div class="item">25%</div> </div> </div>

Use calc :使用calc

 .leftSide { float: left; width: 50px; background-color: green; } .rightSide { float: left; width: calc(100% - 50px); background-color: red; }
 <div style="width:200px"> <div class="leftSide">a</div> <div class="rightSide">b</div> </div>

The problem with this is that all widths must be explicitly defined, either as a value(px and em work fine), or as a percent of something explicitly defined itself.这样做的问题是所有宽度都必须明确定义,要么作为值(px 和 em 工作正常),要么作为明确定义的事物的百分比。

Here, this might help...在这里,这可能会有所帮助...

 <html> <head> <style type="text/css"> div.box { background: #EEE; height: 100px; width: 500px; } div.left { background: #999; float: left; height: 100%; width: auto; } div.right { background: #666; height: 100%; } div.clear { clear: both; height: 1px; overflow: hidden; font-size: 0pt; margin-top: -1px; } </style> </head> <body> <div class="box"> <div class="left">Tree</div> <div class="right">View</div> <div class="clear" /> </div> </body> </html>

If the width of the other column is fixed, how about using the calc CSS function working for all common browsers :如果另一列的宽度是固定的,那么使用适用于所有常见浏览器calc CSS 函数如何:

width: calc(100% - 20px) /* 20px being the first column's width */

This way the width of the second row will be calculated (ie remaining width) and applied responsively.这样,第二行的宽度将被计算(即剩余宽度)并响应应用。

I don't understand why people are willing to work so hard to find a pure-CSS solution for simple columnar layouts that are SO EASY using the old TABLE tag.我不明白为什么人们愿意如此努力地为使用旧的TABLE标签很容易的简单柱状布局找到纯 CSS 解决方案。

All Browsers still have the table layout logic... Call me a dinosaur perhaps, but I say let it help you.所有浏览器仍然具有表格布局逻辑......也许可以称我为恐龙,但我说让它帮助你。

 <table WIDTH=100% border=0 cellspacing=0 cellpadding=2> <tr> <td WIDTH="1" NOWRAP bgcolor="#E0E0E0">Tree</td> <td bgcolor="#F0F0F0">View</td> </tr> </table>

Much less risky in terms of cross-browser compatibility too.在跨浏览器兼容性方面的风险也小得多。

You can try CSS Grid Layout .您可以尝试CSS 网格布局

 dl { display: grid; grid-template-columns: max-content auto; } dt { grid-column: 1; } dd { grid-column: 2; margin: 0; background-color: #ccc; }
 <dl> <dt>lorem ipsum</dt> <dd>dolor sit amet</dd> <dt>carpe</dt> <dd>diem</dd> </dl>

 <html> <head> <style type="text/css"> div.box { background: #EEE; height: 100px; width: 500px; } div.left { background: #999; float: left; height: 100%; width: auto; } div.right { background: #666; height: 100%; } div.clear { clear: both; height: 1px; overflow: hidden; font-size: 0pt; margin-top: -1px; } </style> </head> <body> <div class="box"> <div class="left">Tree</div> <div class="right">View</div> <div class="right">View</div> <div style="width: <=100% getTreeWidth()100 %>">Tree</div> <div class="clear" /> </div> <div class="ColumnWrapper"> <div class="ColumnOneHalf">Tree</div> <div class="ColumnOneHalf">View</div> </div> </body> </html>

A slightly different implementation,一个稍微不同的实现,

Two div panels(content+extra), side by side, content panel expands if extra panel is not present.两个 div 面板(内容+额外),并排,如果extra panel不存在, content panel会展开。

jsfiddle: http://jsfiddle.net/qLTMf/1722/ jsfiddle: http : //jsfiddle.net/qLTMf/1722/

You can use W3's CSS library that contains a class called rest that does just that:您可以使用 W3 的 CSS 库,其中包含一个名为rest的类,它可以做到这一点:

 <link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css"> <div class="w3-row"> <div class="w3-col " style="width:150px"> <p>150px</p> </div> <div class="w3-rest w3-green"> <p>w3-rest</p> </div> </div>

Don't forget to link the CSS library in the page's header :不要忘记在页面的header链接 CSS 库:

<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">

Here's the official demo: W3 School Tryit Editor这是官方演示: W3 School Tryit Editor

This is fairly easy using flexbox.这很容易使用 flexbox。 See the snippet below.请参阅下面的片段。 I've added a wrapper container to control flow and set a global height.我添加了一个包装容器来控制流量并设置全局高度。 Borders have been added as well to identify the elements.还添加了边框以识别元素。 Notice that divs now expand to the full height as well, as required.请注意,div 现在也可以根据需要扩展到整个高度。 Vendor prefixes should be used for flexbox in a real world scenario since is not yet fully supported.供应商前缀应该用于现实世界场景中的 flexbox,因为尚未完全支持。

I've developed a free tool to understand and design layouts using flexbox.我开发了一个免费工具来使用 flexbox 理解和设计布局。 Check it out here: http://algid.com/Flex-Designer在这里查看: http : //algid.com/Flex-Designer

 .container{ height:180px; border:3px solid #00f; display:flex; align-items:stretch; } div { display:flex; border:3px solid #0f0; } .second { display:flex; flex-grow:1; border:3px solid #f00; }
 <div class="container"> <div>Tree</div> <div class="second">View</div> </div>

flex-grow - This defines the ability for a flex item to grow if necessary. flex-grow - 这定义了 flex 项目在必要时增长的能力。 It accepts a unitless value that serves as a proportion.它接受作为比例的无单位值。 It dictates what amount of the available space inside the flex container the item should take up.它决定了项目应该占用 flex 容器内的可用空间量。

If all items have flex-grow set to 1, the remaining space in the container will be distributed equally to all children.如果所有项目都将 flex-grow 设置为 1,则容器中的剩余空间将平均分配给所有子项。 If one of the children has a value of 2, the remaining space would take up twice as much space as the others (or it will try to, at least).如果其中一个孩子的值为 2,则剩余空间将占用两倍于其他空间的空间(或者至少会尝试这样做)。 See more here在这里查看更多

 .parent { display: flex; } .child { flex-grow: 1; // It accepts a unitless value that serves as a proportion } .left { background: red; } .right { background: green; }
 <div class="parent"> <div class="child left"> Left 50% </div> <div class="child right"> Right 50% </div> </div>

Pat - You are right.帕特 - 你是对的。 That's why this solution would satisfy both "dinosaurs" and contemporaries.这就是为什么这个解决方案会同时满足“恐龙”和同时代人的原因。 :) :)

 .btnCont { display: table-layout; width: 500px; } .txtCont { display: table-cell; width: 70%; max-width: 80%; min-width: 20%; } .subCont { display: table-cell; width: 30%; max-width: 80%; min-width: 20%; }
 <div class="btnCont"> <div class="txtCont"> Long text that will auto adjust as it grows. The best part is that the width of the container would not go beyond 500px! </div> <div class="subCont"> This column as well as the entire container works like a table. Isn't Amazing!!! </div> </div>

我不确定这是否是您期望的答案,但是,为什么不将 Tree 的宽度设置为 'auto' 并将 'View' 的宽度设置为 100% ?

Have a look at the available CSS layout frameworks.查看可用的 CSS 布局框架。 I would recommend Simpl or, the slightly more complex, Blueprint framework.我会推荐Simpl或者稍微复杂一点的 Blueprint 框架。

If you are using Simpl (which involves importing just one simpl.css file), you can do this:如果您使用的是 Simpl(只涉及导入一个simpl.css文件),您可以这样做:

<div class="Colum­nOne­Half">Tree</div>
<div class="Colum­nOne­Half">View</div>

, for a 50-50 layout, or : ,对于 50-50 布局,或:

<div class="Colum­nOne­Quarter">Tree</div>
<div class="Colum­nThreeQuarters">View</div>

, for a 25-75 one. ,为 25-75 之一。

It's that simple.就这么简单。

Thanks for the plug of Simpl.css!感谢Simpl.css的插件!

remember to wrap all your columns in ColumnWrapper like so.记得像这样将所有列包装在ColumnWrapper

<div class="ColumnWrapper">
    <div class="Colum­nOne­Half">Tree</div>
    <div class="Colum­nOne­Half">View</div>
</div>

I am about to release version 1.0 of Simpl.css so help spread the word!我即将发布 Simpl.css 的 1.0 版,所以请帮助传播这个词!

I wrote a javascript function that I call from jQuery $(document).ready().我编写了一个从 jQuery $(document).ready() 调用的 javascript 函数。 This will parse all children of the parent div and only update the right most child.这将解析父 div 的所有子级,并且只更新最右边的子级。

html html

...
<div class="stretch">
<div style="padding-left: 5px; padding-right: 5px; display: inline-block;">Some text
</div>
<div class="underline" style="display: inline-block;">Some other text
</div>
</div>
....

javascript javascript

$(document).ready(function(){
    stretchDivs();
});

function stretchDivs() {
    // loop thru each <div> that has class='stretch'
    $("div.stretch").each(function(){
        // get the inner width of this <div> that has class='stretch'
        var totalW = parseInt($(this).css("width"));
        // loop thru each child node
        $(this).children().each(function(){
            // subtract the margins, borders and padding
            totalW -= (parseInt($(this).css("margin-left")) 
                     + parseInt($(this).css("border-left-width")) 
                     + parseInt($(this).css("padding-left"))
                     + parseInt($(this).css("margin-right")) 
                     + parseInt($(this).css("border-right-width")) 
                     + parseInt($(this).css("padding-right")));
            // if this is the last child, we can set its width
            if ($(this).is(":last-child")) {
                $(this).css("width","" + (totalW - 1 /* fudge factor */) + "px");
            } else {
                // this is not the last child, so subtract its width too
                totalW -= parseInt($(this).css("width"));
            }
        });
    });
}

 .container{ display: flex; align-items: stretch; }.resize_overflow { position: relative; width: 0; overflow: hidden; white-space: nowrap; word-wrap: normal; /* text-overflow: ellipsis; When the end of the line dissolves, the ellipsis loses */ }.second_fix { float: right; /* or: display: flex; align-self: end;*/ } /* Dissolve the end of the line at the right edge */.resize_overflow::after { content: ""; /* Empty content */ position: absolute; /* Position relative to parent */ right: 0; /* Element position */ top: 0; /* Element position */ width: 40px; /* Gradient width */ height: 100%; /* Parent Height */ background: -moz-linear-gradient(left, rgba(255,255,255, 0.2), #ff 100%); background: -webkit-linear-gradient(left, rgba(255,255,255, 0.2), #ff 100%); background: -o-linear-gradient(left, rgba(255,255,255, 0.2), #ff 100%); background: -ms-linear-gradient(left, rgba(255,255,255, 0.2), #ff 100%); background: linear-gradient(to right, rgba(255,255,255, 0.2), #ff 100%); }
 <div class="container"> <div class="resize_overflow">Tree</div> <div class="second_fix">View</div> </div>

如果两个宽度都是可变长度,为什么不使用一些脚本或服务器端来计算宽度?

<div style="width: <=% getTreeWidth() %>">Tree</div>

<div style="width: <=% getViewWidth() %>">View</div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM