html - 两列,隐藏一列时,另一列展开全宽

标签 html css flexbox

有没有办法用纯 css 使 2 个 div 占用 50% 的宽度,然后在 一个 上设置一个 css 属性,例如 display:none , 导致另一个占用 100% 宽度?

我正在寻找一种解决方案,我只需要更改其中一个元素的 css,让另一个元素占用其余空间。

最佳答案

您正在寻找的是 flex-grow 属性,它告诉 flex 容器中的元素占用可用空间。

因此,当一行中有两个元素时,它们将占用尽可能多的空间,最终达到 50/50。但如果一个元素被移除,另一个将自动占用剩余空间。

.container {
    display: flex;
}

.box {
    flex-grow: 1;  /* key rule */
    height: 50px;
    border: 1px solid #aaa;
}

.box1 {
    /* display: none; */
    background-color: aqua;
}

.box2 {
    /* display: none; */
    background-color: red;
}
<div class="container">
    <div class="box box1"></div>
    <div class="box box2"></div>
</div>

jsFiddle

flex-grow: 1(或 flex: 1)应用于 flex 容器的子容器(“flex 元素”)告诉它们在它们之间平均分配可用空间。

使用flex-grow: 1:

  • 四个 flex 元素各消耗 25%
  • 三项 = 33.33%
  • 两项 = 50%
  • 一项 = 100%

任何时候删除一个元素,其他元素都会在他们之间分配可用空间。

另请阅读 flex属性,因为规范提出了以下建议:

Authors are encouraged to control flexibility using the flex shorthand rather than with flex-grow directly, as the shorthand resets any unspecified components to accommodate common uses.

source: https://www.w3.org/TR/css-flexbox-1/#propdef-flex-grow


引用资料:


浏览器支持:

所有主流浏览器都支持 Flexbox,except IE 8 & 9 .一些最新的浏览器版本,例如 Safari 8 和 IE10,需要 vendor prefixes .要快速生成前缀,请使用 Autoprefixer .更多详细信息,请参阅 this answer .

关于html - 两列,隐藏一列时,另一列展开全宽,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37039262/

相关文章:

jquery - 在滚动条上更改 css

html - 与图像外的左上角对齐的旋转文本?

html - div的格式(响应式)

jquery - 如何判断popup div是否在浏览器之外

html - 响应式 Bootstrap 网格中内容的垂直和水平居中

php - 组合数字但不在 PHP 中添加它们

javascript - 如何将文本添加到 Highchart 的底部,但在图例上方?

html - 如何使用 flexbox 使 Logo 居中?

javascript - 我们可以在链接到 Javascript 文件时使用 HTML 中的媒体属性吗?

css - 为什么显示: -ms-flex; -ms-justify-content: center; not work in IE10?