gpt4 book ai didi

css - 如何使 flexbox 子项的高度适合内容而不是其容器的 100% 高度

转载 作者:技术小花猫 更新时间:2023-10-29 11:03:41 24 4
gpt4 key购买 nike

#container {
display:flex;
height:300px;
background:#333;
}
#child1 {
width:30%;
background:#3cf;
}
#child2 {
width:30%;
background:#3fc;
}
#child3 {
width:40%;
background:#cf3;
}
#child1_child {
width:100%;
background:#fc3;
}
pre {
margin:0px;
}
    <div id="container">
<div id="child1"><div id="child1_child"><pre>CONTENT<BR>CONTENT<BR>CONTENT<BR>CONTENT</pre></div></div>
<div id="child2"></div>
<div id="child3"></div>
</div>

#child1 的高度自动设置为与#container 相同的高度,如何使其适合#child1_child而不是 #container 的 100% 高度?

#child1_child的高度不是静态的,可以通过里面的内容改变,#child1的高度是静态值是没有用的。

最佳答案

fit-content 的支持有限; IE 永远不会支持它,而 Firefox 仍然需要一个前缀。此解决方案具有仅用于演示目的的 jQuery,并且不是该解决方案所必需的。有四种选择:

  1. NONE: No extra styles on .A
  2. FIT-CONTENT: Adds the CSS property fit-content on .A
  3. MAX-CONTENT: Adds the CSS property max-content on .A
  4. TABLE: Adds the CSS property display:table on .A

选项 2 和 3 的行为相同,所以总而言之,最简单的解决方案是应用 display:table 并且它非常简单,而且非常兼容。 height: fit-contentmax-content 几乎与一个小警告兼容,即 IE 不支持它(IE 正在走恐龙之路,所以它很漂亮很多不是问题)。


演示

$('.rad').on('change', switchStyle);

function switchStyle(e) {
var pick = $(this).val();
switch (pick) {
case 'nil':
$('.A').removeClass('fit max tab');
break;
case 'fit':
$('.A').addClass('fit').removeClass('max tab');
break;
case 'max':
$('.A').addClass('max').removeClass('fit tab');
break;
case 'tab':
$('.A').addClass('tab').removeClass('fit max');
break;
default:
break;
}
}
.box {
display: flex;
height: 300px;
background: #333;
}
.A {
width: 30%;
background: #3cf;
}
.B {
width: 30%;
background: #3fc;
}
.C {
width: 40%;
background: #cf3;
}
.A1 {
width: 100%;
background: #fc3;
}
pre {
margin: 0px;
}
.set {
position: relative;
z-index: 1;
bottom: 300px;
left: 30%;
width: 30ch;
font: 400 16px/1.428 Verdana;
}
.A.fit {
height: -moz-fit-content;
height: -webkit-fit-content;
height: -fit-content;
}
.A.max {
height: max-content;
}
.A.tab {
display: table;
}
<div class="box">
<div class="A">
<div class="A1"><pre>
CONTENT
CONTENT
CONTENT
CONTENT</pre>
</div>
</div>
<div class="B"></div>
<div class="C"></div>
</div>

<fieldset class='set'>
<label>NONE
<input class='rad' name='rad' type='radio' value='nil' checked>
</label>
<label>FIT-CONTENT
<input class='rad' name='rad' type='radio' value='fit'>
</label><br>
<label>MAX-CONTENT
<input class='rad' name='rad' type='radio' value='max'>
</label>
<label>TABLE
<input class='rad' name='rad' type='radio' value='tab'>
</label>
</fieldset>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

关于css - 如何使 flexbox 子项的高度适合内容而不是其容器的 100% 高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35684723/

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