Fixing text overflow when overflow-wrap does not work
- Hemil Ruparel 12 August, 2022
I was writing my first blog over here: Accessing Computer Behind USB tethering in android. While doing that, I wanted to make my page responsive (or at least readable on mobiles). After a bit of searching, I found a property overflow-wrap in CSS which instructs the browser that the text should soft-wrap to the next line essentially. Mozilla MDN has excellent reference for HTML, CSS and JS. The reference to overflow property is here
I was like great I am done. Unfortunately, I wasnt. Even after I had set the property, it had no effect. I was using firefox dev tools in the size 465 by 622 pixels to simulate a phone. Lets explore the problem:
Conclusion: When working with overflow-wrap, ensure you have a width less than your content
Go through the DOM in inspect element of your browser of choice. Find the first parent element with width greater than what you expect. And give a width or max-width to it. In my case, setting max-width: 100% for main worked. The browser then didnt even need overflow-wrap.
How I solved it
To elaborate, in my html, the root was html tag. It had 1 child - body. Body had 3 children - aside, main and aside in that order. Inside main, there is content that is overflowing. So, what I have to do is walk up this tree and find the first element with has much greater width than expected.
The immediate parent of overflowing content in main. I hover over it which shows me its size in Firefox. It is 824 by 12000 pixels. Okay. Next I go up to body. Body is 449 by 12000. Interesting. So, that means the device is rougly 450 pixels wide. Why is it taking up so much space?
If contents are too big to fit in a given area, by default browsers will overflow the content in surrounding areas to ensure no loss of information. This is really important to remember. My text was too big to be displayed in 450 pixels wide. So browser let it overflow and then added a horizontal scroll bar to compensate. Problem is, overflow-wrap depends on width. If you have enough width, overflow-wrap would do nothing (obviously!).