gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 12:32:19 25 4
gpt4 key购买 nike

有没有办法用纯 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com