在css中使用overflow-y和height auto

时间:2015-06-01 17:13:41

标签: css scrollbar

我确实有一个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;
}

3 个答案:

答案 0 :(得分:5)

听起来你可能正在寻找https://groups.google.com/forum/#!topic/parse-developers/WoRnDft4qmE,这会将div高度限制为所提供的值。

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

答案 1 :(得分:2)

您可以设置固定高度。或者设置最大高度的CSS样式。如果您希望它达到不超过500px,例如,您可以调用

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

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

答案 2 :(得分:0)

只要父容器具有设定的高度,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>