Keep text in div

Viewed 43

If I do:

<div style="width: 200px; height: 200px; background-color: yellow; font-size: xx-large;">
    Hello 1<br>
    Hello 2<br>
    Hello 3<br>
    Hello 4<br>
    Hello 5<br>
    Hello 6<br>
    Hello 7<be>
</div>

The text bleeds out of the DIV. I want it to either cut the display of the text off or put scrollbars. Anything but have the text just exit the DIV! I understand that this is basically what the <textarea> does, but I'm trying not to use that tag for other reasons.

Sure appreciate any help!

Thanks!

3 Answers

You can leverage overflow-y to force a scrollbar on the y-axis.

Which produces:

    <div style="overflow-y:auto;width: 200px; height: 200px; background-color: yellow; font-size: xx-large;">
        Hello 1<br>
        Hello 2<br>
        Hello 3<br>
        Hello 4<br>
        Hello 5<br>
        Hello 6<br>
        Hello 7<be>
    </div>

If you want to cut out the redundant text, you can use overflow:hidden which hides text that exceeds the width and height.

<div style="width: 200px; overflow:hidden;height: 200px; background-color: yellow; font-size: xx-large;">
        Hello 1<br>
        Hello 2<br>
        Hello 3<br>
        Hello 4<br>
        Hello 5<br>
        Hello 6<br>
        Hello 7<be>
    </div>

You're looking for the overflow property

overflow: hidden will hide the text that is outside of the container with no scroll bar

overflow: scroll will always show a scrollbar

overflow: auto will automatically show a scrollbar if the text starts to go beyond the edge of the container

div {
  width: 200px;
  height: 200px;
  background-color: yellow;
  font-size: xx-large;
  overflow: auto;
}
<div>
  Hello 1<br>
  Hello 2<br>
  Hello 3<br>
  Hello 4<br>
  Hello 5<br>
  Hello 6<br>
  Hello 7<br>
</div>

Remove width: 200px; height: 200px; from style if you want to keep the field as big as the given text

Related