Search code examples
htmlcssweb-crawlersemantic-markupscreen-readers

How to make selectable text different from what's displayed


I need to create a heavily styled bit of text that doesn't display a specific character visually, but does contain the character for other purposes. For example, the UI might show something like $12345, but the underlying text is actually $123.45.

  • If you select the displayed text and Ctrl+C, the clipboard should actually contain the underlying text.
  • If you select the displayed text and right-click, the context menu should have an option along the lines of Search Google for "X" where X is the underlying text (assuming the browser supports it).
  • Both screen readers and webcrawlers should 'see' the underlying text.

Here's my current solution:

body {
  font-family: sans-serif;
}

.price {
  line-height: 4.4rem;
  font-size: 4rem;
}

.cc, .cf {
  font-size: 0.6em;
  vertical-align: super;
  margin: 0 2px;
}

.cs {
  opacity: 0;
  margin: 0 0 0 -.28em;
}

.ci {
  font-size: 4.4rem;
}
<span class="price" aria-label="$123.45">
  <span class="cc">$</span><span class="ci">123</span><span class="cs">.</span><span class="cf">45</span>
</span>

However, I'm not sure if having an invisible (opacity: 0) element is really the best way to do this—it feels a bit underhanded and possibly some smart crawlers may see it that way too. Also, the -.28em is not scalable—that's just the best number I could find to look good and I'd have to tweak it for different fonts or font sizes.

I could change the .cs to display: inline-block; width: 0 to get around the margin issue, but then if you double-click on the 123 to select the 'word' or triple-click to select the block, the 45 is not selected. So keeping the .cs inline seems important to ensuring that the whole text is treated as one continuous piece of text.

So my question is, using HTML5 and CSS, what is the semantically correct way to have different content that gets selected than what's displayed?


Solution

  • Font size 0 is an alternative that you can try for the period.

    .cs {
     font-size: 0;
    }
    

    The information will be retained as per your requirement both on screen reader and on clipboard