Is it possible to use hyphens or soft hyphens in CSS so that hyphens do not appear unnecessarily?
My goal is to keep the source text as much as possible and break any words if they are not absolutely critical, because they are too long to fit the width of the container.
My specific case
I want to make the text "Hi Superman" so that:
If the word "Superman" is too long to fit inside the container, I want to somehow rephrase it, for example:
Hi Super- man
But if the word "Superman" can fit in a container, it should display without a hyphen
Hi Superman
If the above case ("Superman" can be written loose), UNACCEPTABLE can add unnecessary hyphens as follows:
Hi Super- man
I can change the HTML, but I want to. I am allowed to enter hyphens in such a way that it makes sense (as long as there are more than three letters between these hyphens. "Superma-n" is never okay)
What i tried
I thought soft hyphens would be the solution. So I used: Hi Super­man
But I found out that this will lead to an unacceptable case of "unnecessary hyphenation", shown above.
Snapshot to show failure:
body { margin-left: 30px; } div { border: solid 1px black; } .wide { border: solid 1px blue; width: 500px; } .narrow { border: solid 1px red; width: 360px; } h2 { font-family: 'Courier New'; font-weight: 400; font-size: 87px; } code { background-color: #eee; }
<p> <code>Super&shy;man</code> looks good in really narrow containers where the full word "Superman" would not fit</p> <p> <div class="narrow"><h2>Hi Super­man</h2></div> <p>But in this case the word "Superman" would fit unhypenhated on the second row. But the damn CSS decides to add hyphens anyway. Unacceptable in my case! Again, this uses the same code as the previous example <code>Super&shy;man</code></p> <div class="wide"><h2>Hi Super­man</h2></div> <p>I even tried adding a wordbreak tag before "Superman", like this <code>Hi <wbr> Super&shy;man</code> but it does not help</p> <p> </p> <div class="wide"><h2>Hi <wbr>Super­man</h2></div>
Can I solve the above example using only CSS? (Tried different word-break properties without any success)
My guess is that this cannot be solved with simple HTML and CSS due to the nature of CSS. I assume that CSS simply parses the text line by line, and it will never be able to find out if the word "matches" in the next line of text. If he finds a hyphen, he will try to set the maximum number of characters in the current line of text.
I want to solve this only with HTML and CSS or not at all. Edit : Preferred -Not text-parsing with javascript.
- I do not need to set different CSS properties for each div, based on how big the div is and whether I believe that the text will need to be wrapped or not.
- You did not need to add wrappers around my words
-Not auto-hyphenation, which can lead to ridiculous hyphenation, such as "Superma-n" (however, in the extreme case, I would be okay with auto-autophorepy until there are 3 characters between each def. Similar to "Sup -erman ")