Search code examples
htmlcssword-break

Indicate a broken line in HTML (due to word-break)


I want to indicate that a line has been broken (due to word-break CSS property) with an icon (see screenshot of how VS2019 is doing that). I need this because I'm displaying code in HTML with code or pre elements. Do you have an idea of how to solve this in a simple way (preferably CSS)?

Linebreaks in VS2019


Solution

  • Here's a mostly-pure-CSS version that uses a repeating background image. The JavaScript is only required to split the content on hard line breaks. The CSS variable could be hard-coded or use SCSS variables etc if legacy browser support required.

    const target = document.querySelector('#target')
    
    const lines = target.textContent.split('\n').map(str => {
      const div = document.createElement('div')
      div.classList.add('line')
      div.textContent = str
    
      return div
    })
    
    target.textContent = ''
    lines.forEach(line => target.appendChild(line))
    :root {
      --line-height: 20px;
    }
    
    #target {
      white-space: pre-wrap
    }
    
    .line {
      display: flex;
      padding-right: var(--line-height);
      line-height: var(--line-height);
      position: relative;
    }
    
    .line:nth-child(odd) {
      background: #f8f8f8;
    }
    
    .line::after {
      content: '';
      position: absolute;
      right: 0;
      height: calc(100% - var(--line-height));
      background-repeat: repeat-y;
      background-size: var(--line-height) var(--line-height);
      width: var(--line-height);
      font-weight: bold;
      color: #269;
      opacity: .3;
      background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='40' height='40'%3E%3Cg%3E%3Crect fill='none' id='canvas_background' height='42' width='42' y='-1' x='-1'/%3E%3C/g%3E%3Cg%3E%3Cpolygon id='svg_1' points='16.397236347198486,20.219151496887207 9.397236347198486,25.219151496887207 16.397236347198486,30.219151496887207 '/%3E%3Cpath id='svg_2' d='m27.39724,10.21915l0,9c0,3.3 -2.7,6 -6,6l-8,0' stroke-miterlimit='10' stroke-width='4' stroke='%23000000' fill='none'/%3E%3C/g%3E%3C/svg%3E");
    }
    <pre id="target">Lorem ipsum dolor sit amet.
    Consectetur adipisicing elit.
    Debitis vero dolorem officia omnis nulla molestiae perferendis sequi illo.
    Molestiae error inventore perspiciatis maxime?
    At, illum!
    Cupiditate consequuntur harum minima perferendis recusandae alias, rem, vitae dolor quo fuga, facilis sunt dolorem sint perspiciatis eveniet suscipit inventore illo unde animi saepe officiis assumenda laboriosam error.
    Incidunt, dolorem ullam ipsa enim odit minima et cumque impedit?
    Suscipit corrupti voluptates placeat, aliquam nesciunt minima ipsum debitis pariatur atque incidunt nobis facere iure numquam assumenda officiis facilis.</pre>