Incorrect scrollWidth on child of flex container

坚强是说给别人听的谎言 提交于 2021-01-27 19:00:35

问题


According to w3schools:

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).

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>

回答1:


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.

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

Example:

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>


来源:https://stackoverflow.com/questions/56470839/incorrect-scrollwidth-on-child-of-flex-container

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!