如何在不指定宽度的情况下使div占据所有可用的剩余水平空间?

时间:2019-12-05 21:00:54

标签: html css flexbox

我需要创建两个div:一个(右侧)小div,不包含短文本,另一个(左侧)大,占据屏幕的剩余空间,并将文本包装在需要。我正在尝试以下方法:

html,body {
  margin: 0;
  height: 100%;
}
body {
  display: flex;
  align-items: stretch;
}
#divL {
  background-color: green;
  flex: 1 0 auto;
  padding: 1em;
}
#divR {
  background-color: red;
  white-space: nowrap;
  padding-left: 1em;
  padding-right: 1.5em;
  overflow-y: auto;
}
<div id='divL'>
a short text
</div>
<div id='divR'>
<p>list of items</p>
<p>list of items</p>
<p>list of items</p>
<p>list of items</p>
<p>list of items</p>
<p>list of items</p>
<p>list of items</p>
<p>list of items</p>
<p>list of items</p>
<p>list of items</p>
<p>list of items</p>
<p>list of items</p>
<p>list of items</p>
<p>list of items</p>
</div>

到目前为止,太好了。但是左侧面板会与文本一起增加,当文本太大时将右侧面板推出屏幕:

html,body {
  margin: 0;
  height: 100%;
}
body {
  display: flex;
  align-items: stretch;
}
#divL {
  background-color: green;
  flex: 1 0 auto;
  padding: 1em;
}
#divR {
  background-color: red;
  white-space: nowrap;
  padding-left: 1em;
  padding-right: 1.5em;
  overflow-y: auto;
}
<div id='divL'>
very long text very long text very long text very long text very long text very long text very long text very long text very long text very long text very long text very long text 
</div>
<div id='divR'>
<p>list of items</p>
<p>list of items</p>
<p>list of items</p>
<p>list of items</p>
<p>list of items</p>
<p>list of items</p>
<p>list of items</p>
<p>list of items</p>
<p>list of items</p>
<p>list of items</p>
<p>list of items</p>
<p>list of items</p>
<p>list of items</p>
<p>list of items</p>
</div>

我不想指定固定宽度,因为右侧面板的宽度可变(不要太大,每行只有两个或三个词)。如何实现这种简单的设计?不用在某处指定固定宽度就可以吗?

2 个答案:

答案 0 :(得分:2)

问题出在这一行:

flex: 1 0 auto;

这是以下简称:

flex-grow: 1;
flex-shrink: 0;
flex-basis: auto;

请参阅:https://developer.mozilla.org/en-US/docs/Web/CSS/flex

有问题的部分是flex-shrink: 0。这表示左div根本不应该缩小。

相反,请尝试:

flex: 1 1 auto;

进一步:flex-shrink的默认值为1flex-basis的默认值为auto。如果3个属性中的2个具有默认值,我将完全不使用速记flex。我只需要指定一个不需要默认的属性即可:

flex-grow: 1;

答案 1 :(得分:1)

那是你想要的吗?

    html,body {
      margin: 0;
    }
    body {
      display: flex;
    }
    #divL {
      background-color: green;
      flex: 1;
    }
    #divR {
      background-color: red;
    }
<div id='divL'>
    very long text very long text very long text very long text very long text very long text very long text very long text very long text very long text very long text very long text 
    </div>
    <div id='divR'>
    <p>list of items</p>
    <p>list of items</p>
    <p>list of items</p>
    <p>list of items</p>
    <p>list of items</p>
    <p>list of items</p>
    <p>list of items</p>
    <p>list of items</p>
    <p>list of items</p>
    <p>list of items</p>
    <p>list of items</p>
    <p>list of items</p>
    <p>list of items</p>
    <p>list of items</p>
    </div>