在 css 中使用 overflow-y 和 height auto

Using overflow-y with height auto in css

我确实有一个 div,如果其中的文本太大,我希望在其中显示滚动条 (overflow-y: auto; height: 300px;)。但是,我的 div 已经包含了 属性 height:auto;(为了垂直对齐)。无论如何我可以保留 height:auto 并且在需要时仍然显示滚动条吗?

HTML:

<div class = 'valign scrollbar'>
 My Text
</div>

CSS:

.valign {
 height: auto;
}

.scrollbar {
 height: 300px;
 overflow-y: auto;
}

您可以设置固定高度。或者设置一个 max-height css 样式。如果你希望它达到不超过 500px,例如你可以调用

.scrollbar {
  max-height:500px;
  overflow-y: auto;
}

这应该可以帮助您限制元素的大小。

听起来您可能正在寻找 max-height,这会将 div 高度限制为提供的值。

.scrollbar {
   max-height: 300px;
   overflow-y: auto;
}

只要父容器设置了高度,max-height: 100%;似乎就可以了。

.container {
  background-color: green;
  height: 400px;
  width: 400px;
}

.valign {
  height: auto;
}

.scrollbar {
  max-height: 100%;
  overflow-y: auto;
  background-color: red;
}
<div class="container">
  <div class='valign scrollbar'>
    Short: Standard Lorem Ipsum passage, used since the 1500s:
  </div>
</div>
<br><br>


<div class="container">
  <div class='valign scrollbar'>
    Long: Standard Lorem Ipsum passage, used since the 1500s:
    <br><br> 
    "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
    <br><br> 
    1914 translation by H. Rackham
    <br><br> 
    "On the other hand, we denounce with righteous indignation and dislike men who are so beguiled and demoralized by the charms of pleasure of the moment, so blinded by desire, that they cannot foresee the pain and trouble that are bound to ensue; and equal blame belongs to those who fail in their duty through weakness of will, which is the same as saying through shrinking from toil and pain. These cases are perfectly simple and easy to distinguish. In a free hour, when our power of choice is untrammelled and when nothing prevents our being able to do what we like best, every pleasure is to be welcomed and every pain avoided. But in certain circumstances and owing to the claims of duty or the obligations of business it will frequently occur that pleasures have to be repudiated and annoyances accepted. The wise man therefore always holds in these matters to this principle of selection: he rejects pleasures to secure other greater pleasures, or else he endures pains to avoid worse pains."
  </div>
</div>