为什么overflow-y属性不能与高度百分比一起使用

问题描述:

我试图将百分比高度与overflow-y:auto;一起使用,而不是在div的侧面创建滚动条,而是使用页面滚动条.

I'm trying to use percentage height with overflow-y:auto; and instead of creating a scroll bar on the side of the div, it's using the page scroll bar.

以下是我想要的示例: http://jsfiddle.net/hmwe2jty/

Here's an example of want I'm getting at: http://jsfiddle.net/hmwe2jty/

是否可以使用百分比高度的属性?

Is it possible to use this property with percent height?

TL; DR 使用视口高度/宽度而不是百分比.将100%更改为100vh,您就完成了!

TL;DR Use the viewport height/width instead of a percentage. Change 100% to 100vh, and you're done!

百分比取父元素的百分比.例如:

The percentages take the precentage of the parent element. For example:

console.log("Parent's width: " + document.getElementById("parent").offsetWidth);
console.log("Child's width: " + document.getElementById("child").offsetWidth);

#parent {
  background: yellow;
  width: 500px;
  height: 150px;
}

#child {
  background: orange;
  width: 50%;
  height: 100px;
}

<div id="parent">
  <div id="child">
    I am 250px wide!
  </div>
</div>

新的CSS3视口单元将用户的视口用作基础.例如:

The new CSS3 viewport units use the user's viewport as a base. For example:

console.log("Parent's width: " + document.getElementById("parent").offsetWidth);
console.log("Child's width: " + document.getElementById("child").offsetWidth);

#parent {
  background: yellow;
  width: 500px;
  height: 150px;
}

#child {
  background: orange;
  width: 50vw;
  height: 100px;
}

<div id="parent">
  <div id="child">
    My width is 50% of the user's viewport, regardless of the size of my parent!
  </div>
</div>

由于body元素有点怪异,因此默认行为是缩小以适合内容.所以:

Because the body element is a bit weird, it's default behaviour is to shrink to fit is contents. So:

body {
  background: yellow;
  border: 1px solid red;
}

The body element wraps around it contents, <br>
but the backgound just ignores this behaviour.

因此,由于父元素是主体,因此您将需要使用新的vw和vh单位.阅读 CSS技巧

So, since the parent element is the body, you will need to use the new vw and vh units. Read a article on CSS Tricks

将视口选择为父级的另一种方法是使元素的位置为fixedabsolute.在这种情况下,父级将成为视口,从而为您提供所需的值.

Another way to choose the viewport as parent would be to make the element's position either fixed or absolute. In that instance the parent would become the viewport, thus giving you the needed value.