我正在使用 CSS Flex 以便在包装器中显示三个相应的 DIV。
第一个 DIV (item0
) 的宽度尺寸为 50px。
我需要更改 wrapper
的高度,并保持包装内 item0
和 item1
DIV 的原始宽度。
我目前的问题是:
- 当调整
wrapper
大小时,flex 元素 (item0
) 获得不同的width
。尺寸
请点击示例中的两个按钮,查看尺寸的变化。
我想知道:
- 为什么宽度尺寸改变了?
- 如何保持
item0
和item2
的宽度大小与我原来的 CSS 设置相同?
注意事项:
我知道滚动条会占用空间。我怎样才能将 item0
和 item2
保持在固定宽度,而 item1
拉伸(stretch)以填满剩余空间? (我尝试使用 %
但我无法获得想要的结果)。
var btn0 = document.getElementById('btn0');
var btn1 = document.getElementById('btn1');
var item0 = document.getElementById('item0');
var result = document.getElementById('result');
var wrapper = document.getElementById('wrapper');
btn0.addEventListener('click', function(event) {
wrapper.style.height = '25px';
result.value = item0.getBoundingClientRect().width;
});
btn1.addEventListener('click', function(event) {
wrapper.style.height = '350px';
result.value = item0.getBoundingClientRect().width;
});
#wrapper {
width: 250px;
height: 350px;
background-color: gray;
overflow: auto;
}
#flex-container {
display: flex;
}
#item0 {
width: 50px;
background-color: red;
height: 150px;
}
#item1 {
width: 150px;
background-color: orange;
height: 150px;
}
#item2 {
width: 50px;
background-color: pink;
height: 150px;
}
<div id="wrapper">
<div id="flex-container">
<div id="item0" class="item">a
</div>
<div id="item1" class="item">b
</div>
<div id="item2" class="item">c
</div>
</div>
</div>
<button id='btn0' type="button">Smaller wrapper</button>
<button id='btn1' type="button">Bigger wrapper</button>
item0 width is: <input id="result"type="text">
最佳答案
为 item0 样式使用 flex: 0 0 50px
。
参见 jsfiddle
它告诉 flexbox 布局不要增长也不要收缩,并给它一个 50px 的宽度。
对 flexbox 元素使用 flex: 属性总是好的,因为它的默认值可能因浏览器而异。 (例如,实际上您的问题不会发生在 firefox 中)
关于javascript - CSS Flex - 当调整包装器 flex 元素的大小时改变它的宽度尺寸,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36403232/