Flex容器的子代上的scrollWidth不正确 [英] Incorrect scrollWidth on child of flex container

查看:23
本文介绍了Flex容器的子代上的scrollWidth不正确的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据 w3schools :

scrollWidth scrollHeight 属性返回元素的整个高度和宽度,包括不可见的高度和宽度(由于溢出).

The scrollWidth and scrollHeight properties return the entire height and width of an element, including the height and width that is not viewable (because of overflow).

如果是这种情况,为什么在较小的 flex 父级元素内的元素的 scrollWidth 仅报告为可见部分?

If that's the case, why is the scrollWidth of an element inside a narrower flex parent reported as the visible portion only?

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>

推荐答案

在某些用作容器的元素上使用 display:flex 时,该容器内的元素的宽度将缩小以适合容器的宽度.这实际上是 flexbox 的本质,重要的是您要做出响应式布局.

When you use display:flex on some element that acts as a container, the elements inside that container will shrink in width to fit the container's width. This is actually the essence of flexbox and it is important is you want to make a responsive layout.

但是,您可以使用 flex-shrink:0 可以防止某些特定元素出现这种情况,但是我不确定为什么会这样.

However, you can use flex-shrink: 0 to prevent this for some particular element, but I'm not sure why you would want that.

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>

这篇关于Flex容器的子代上的scrollWidth不正确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆