Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
90 views
in Technique[技术] by (71.8m points)

javascript - CSS scrolling with top overflow

I am trying to make div elements containing short text strings appear (using JS) in the middle of a blank page, with new elements always centered and older elements moving upwards (similar to what a console or terminal session would look like). Elements that disappear at the top of the page should be viewed by scrolling upwards (i.e. back in time).

The following code works but scroll bars don't appear. Why is that?

HTML

#wordlist {
  position: fixed;
  overflow: scroll;
  margin: 0 auto;
  bottom: 50%;
  left: 40%;
  text-align: left;
}

.word {
  // Just font and color
}
<body>
  <div id="wordlist">
    <div class="word">whatever</div>
    <div class="word">whatever</div>
    <div class="word">whatever</div>
    <div class="word" id="current">whatever</div>
  </div>
</body>
question from:https://stackoverflow.com/questions/66060216/css-scrolling-with-top-overflow

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try this.

Add a max-height to the div. This will make sure that the height of the div shouldn't go beyond the max-height. Then, add overflow: auto. This will make sure that when the height goes beyond the max-height, scrollbars should appear.

overflow: auto; works for both width and height. If you want to be specify, you can always go for overflow-y: auto;.

Also, I forgot to mention that max-height will not unnecessarily maintain a fixed height if the children are less.

#wordlist {
  position: fixed;
  overflow: auto;
  margin: 0 auto;
  max-height: 100px;
  bottom: 50%;
  left: 40%;
  text-align: left;
}

.word {
  // Just font and color
}
<body>
  <div id="wordlist">
    <div class="word">whatever</div>
    <div class="word">whatever</div>
    <div class="word">whatever</div>
    <div class="word">whatever</div>
    <div class="word">whatever</div>
    <div class="word">whatever</div>
    <div class="word">whatever</div>
    <div class="word">whatever</div>
    <div class="word" id="current">whatever</div>
  </div>
</body>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...