Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why hyphens don't work with inner <span>?

I'm trying to get hyphens working on text that has <span> elements inside for highlighting. This seems to break the hyphen algorithm. Is there any way to fix the behaviour so that hyphens are placed the same as without <span> elements? I'm not asking about a workaround like &shy;

enter image description here

The Code (sandbox: https://codepen.io/anon/pen/ayzxpM):

.limit {
  max-width: 50px;
  hyphens: auto;
  font-size: 20px;
  background-color: #eee;
}

span {
  color: red;
}
<div class="limit">
  <p>
    Appletreefruitthing
  </p>
  <p>
    Apple<span>tree</span>fruitthing
  </p>
</div>

Using the lang attribute

Adding the lang attribute as Vadim Ovchinnikov suggested (<div class="limit" lang="en">) can lead better results on some platform/browser combinations. On Firefox 54, Windows 10 this is the result:

enter image description here

But even that seems buggy. The hyphen should be black in my opinon and the hyphen algorithm seems to miss the chance to make a line break between "fruit" and "tree", also completly ignoring the max-width that is set for the container.

like image 546
tobias47n9e Avatar asked Oct 17 '22 08:10

tobias47n9e


1 Answers

Actually, it does work with spans, in a number of browsers. You just used a word that is not recognized. Here's an example with a normal English word, that works in IE (should also work in Edge) and FF on Win7:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, user-scalable=yes, initial-scale=1">
    <title>Demo</title>
<style>
div {
    max-width: 50px;
    -webkit-hyphens: auto;
    -moz-hyphens: auto;
    -ms-hyphens: auto;
    hyphens: auto;
    font-size: 20px;
    background-color: #eee;
}
span {
    color: red;
}
</style>
</head>
<body>
    <div>
        <p>Incomprehensibilities</p>
        <p>Incom<span>pre</span>hensibilities</p>
    </div>
</body>
</html>

It does not work in Chrome on Win, because that currently (June 2018) still does not support hyphens at all. It also does not work in any iOS browser. So you will have to use soft hyphens after all. But as you stated that you were curious about the mechanism, I thought it worthwhile to still post this answer.

like image 169
Frank Conijn Avatar answered Nov 15 '22 08:11

Frank Conijn