为什么溢出:隐藏影响宽度

时间:2016-08-25 10:12:22

标签: html css flexbox overflow

在以下代码中,在 #content 规则中,overflow:hidden为自动调整div的width做了一些魔术。我尝试在 #content 中手动将宽度设置为某个值,例如10000px,但宽度不起作用。如果我使用overflow:hidden|scroll|auto,则确定宽度。

我只是想知道为什么overflow:hidden会有魔力?

我已经研究过overflow:hidden可能会启动BFC的可能性。但display:flex与BFC具有相同的效果。

更具体地说,我最初的尝试是让 #content 省略号中的所有文字逐行排列。我发现在 #content 中设置width可以正常工作。但是我意外地发现我可以overflow:hidden在不设置宽度的情况下做同样的事情。那为什么会这样呢?

#container {
  padding: 12px;
  display: flex;
}

#leftblock {
  width: 100px;
  height: 100px;
  background-color: #ccc;
}

#content {
  margin-left: 10px;
  display: flex;
  flex-direction: column;
  flex: 1;
  overflow: hidden;
}

p {
  text-overflow: ellipsis;
  white-space: nowrap;
  overflow: hidden;
  margin: 8px 0;
}
<div id="container">
  <div id="leftblock"></div>   
  <div id="content">
    <p><b>This div will take the rest of the available width, and the <code>overflow:hidden;</code> makes sure this text doesn't fall below the <code>#floated</code> div.</b></p>

    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce tincidunt vestibulum magna, nec rutrum lacus lobortis at. Duis convallis tincidunt neque eu viverra. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam condimentum faucibus mauris, pretium varius dui tempor tempor. Aenean in elit dolor, a pellentesque urna. Vestibulum egestas metus id massa elementum quis posuere nunc tincidunt. Curabitur dapibus dictum lacus a fermentum.</p>

    <p>Quisque cursus gravida sem quis pretium. Cras cursus, neque sit amet bibendum ornare, nunc mi euismod ligula, ut cursus enim risus nec mi.</p>
  </div>
</div>

1 个答案:

答案 0 :(得分:0)

完全更新:

#container {
        width:500px;
        padding: 12px;
        display: flex;
        flex-wrap: wrap;
    }

    #floated {
        width: 100px;
        height: 100px;
        background-color: #ccc;
    }

    #content {
        margin-left: 10px;
        display: flex;
        flex-direction: column;
        flex: 1;
    }

    p {
        text-overflow: ellipsis;
        margin: 8px 0;
    }
<div id="container">
    <div id="floated"></div>
    <div id="content">
        <p><b>This div will take the rest of the available width, and the makes sure this text doesn't fall below the <code>#floated</code> div.</b></p>

        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce tincidunt vestibulum magna, nec rutrum lacus lobortis at. Duis convallis tincidunt neque eu viverra. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam condimentum faucibus mauris, pretium varius dui tempor tempor. Aenean in elit dolor, a pellentesque urna. Vestibulum egestas metus id massa elementum quis posuere nunc tincidunt. Curabitur dapibus dictum lacus a fermentum.</p>

        <p>Quisque cursus gravida sem quis pretium. Cras cursus, neque sit amet bibendum ornare, nunc mi euismod ligula, ut cursus enim risus nec mi.</p>
    </div>
</div>

更新:您通过.container确定宽度,因为flex:1;将占用容器中剩余的空间。我缩小了容器,向你展示。