csscss-hyphens

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.


Solution

  • Chrome has only partial support for hyphens property (only Mac and Android platforms), so you can't make it work on Windows.

    I don't see any difference between span presence and absence in Firefox, IE and Edge (all on Windows) for this code.

    To make it work there you'll need set lang for container and add vendor prefixes (for -ms-hyphens IE/Edge and -webkit-hyphens for Safari). Demo:

    .limit {
      max-width: 50px;
      font-size: 20px;
      /* Safari */
      -webkit-hyphens: auto;
      /* IE, Edge */
      -ms-hyphens: auto;
      hyphens: auto;
      background-color: #eee;
    }
    
    span {
      color: red;
    }
    <div class="limit" lang="en">
      <p>
       Appletreefruitthing
      </p>
      <p>
        Apple<span>tree</span>fruitthing
      </p>
    </div>


    To work in all browsers you may shouldn't use CSS hyphens property, just insert &shy; manually where you want hyphens.

    .limit {
      max-width: 50px;
      font-size: 20px;
      background-color: #eee;
    }
    
    span {
      color: red;
    }
    <div class="limit">
      <p>
       Apple&shy;tree&shy;fruitthing
      </p>
      <p>
        Apple&shy;<span>tree</span>&shy;fruitthing
      </p>
    </div>