根据w3schools:
scrollWidth 和 scrollHeight 属性返回元素的整个高度和宽度,包括不可见的高度和宽度(由于溢出)。
如果是这种情况,为什么在较小的 flex 父级元素内的元素的 scrollWidth 仅报告为可见部分?
document.body.append("Bar 1 scrollWidth = " + document.getElementById("inner1").scrollWidth);
document.body.appendChild(document.createElement("br"));
document.body.append("Bar 2 scrollWidth = " + document.getElementById("inner2").scrollWidth);
div {
outline: 1px solid grey;
margin-bottom: 10px;
}
.outer {
width: 200px;
background-color: yellow;
padding: 3px;
}
.inner {
width: 300px;
position: relative;
display: inline-block;
background-color: pink;
}
#outer2 {
display: flex;
background-color: lightgreen;
}
<div class="outer" id="outer1">
<div class="inner" id="inner1">Bar 1</div>
</div>
<div class="outer" id="outer2">
<div class="inner" id="inner2">Bar 2</div>
</div>
答案 0 :(得分:1)
在用作容器的某些元素上使用display:flex
时,该容器内的元素的宽度将缩小以适合容器的宽度。这实际上是flexbox
的本质,重要的是您要制作响应式布局。
但是,您可以使用flex-shrink: 0来防止某些特定元素出现这种情况,但是我不确定为什么会这样。
document.body.append("Bar 1 scrollWidth = " + document.getElementById("inner1").scrollWidth);
document.body.appendChild(document.createElement("br"));
document.body.append("Bar 2 scrollWidth = " + document.getElementById("inner2").scrollWidth);
div {
outline: 1px solid grey;
margin-bottom: 10px;
}
.outer {
width: 200px;
background-color: yellow;
padding: 3px;
}
.inner {
width: 300px;
position: relative;
display: inline-block;
background-color: pink;
}
#outer2 {
display: flex;
background-color: lightgreen;
}
#inner2 {
flex-shrink: 0;
}
<div class="outer" id="outer1">
<div class="inner" id="inner1">Bar 1</div>
</div>
<div class="outer" id="outer2">
<div class="inner" id="inner2">Bar 2</div>
</div>