How to ensure full scrolling text coverage when using CSS property 'Overflow: scroll' on a div
P粉321584263
2023-08-16 00:13:42
<p>I am new to programming and currently trying to make a simple one-page website using HTML/CSS and JS. I have a CSS class called 'general_container' in which I write text, which is also defined in CSS as 'div_text' (code for both is provided below): </p>
<pre class="brush:php;toolbar:false;">.general_container{
margin: min(1vw,1vh) min(1vw,1vh);
display: flex;
height: fit-content;
width: fit-content;
max-width: 100%;
max-height: 80vh;
position: relative;
padding: min(1vw,1vh);
border-color: #232323;
border-style: solid;
border-width: 0.2rem;
border-radius: 1rem;
align-items: center;
justify-content:center;
overflow-x: hidden;
overflow-y: auto;
}
.div_text {
font-size: calc(12px 1.5vw);
color: #F2F2F2;
position: relative;
}</pre>
<p>The problem arises when the text is large compared to the div it is in: using the font size defined above, on my native resolution (2560x1440) the text is hidden and accessible via the scrollbar. However, the top of the scrollbar does not show the beginning of the text as shown in the image below (I used a generic placeholder text). </p>
<p>I'm guessing that dynamic font sizes and constraints on div sizes are the cause of this behavior, but I don't know how to fix it. </p>
<p>Image with text not accessible via scrollbar</p>
<p> I tried modifying the div's constraints and overflow properties, but from what I read on the official Mozilla webdev guide, using overflow-y: scroll (auto defaults to scroll in this case) does what I want it to do Work. If you add more text, increasing max-height will cause the same problem. </p>
Remove the align-items:center; rule.
To ensure that the scrollbar starts at the top and covers the entire text content, make the following changes: Remove
justify-content: center;
from.general_container
. Removeheight: fit-content;
andwidth: fit-content;
from.general_container
. Set a specificmax-height
for.general_container
to limit its height.Example