Offscreen Text for Copy & Paste

By  on  

The relationship between HTML and CSS is special: mixing content via HTML with presentation from CSS to make an awesome presentation. Sometimes, however, you need to employ CSS tricks solely to enhance functionality. This could be one of those cases.

When browsing through the Firefox DevTools console code, I noticed a really clever technique for hiding text on screen but making sure it's present during a copy + paste. Here's the technique:

<p>Jenny don't change your number <span class="copy-only">8675309</span></p>
.copy-only {
  display: block;
  position: absolute;
  left: -9999999px;
  top: -9999999px;
}

With the CSS above, the screen displays "Jenny don't change your number" while copying that line would result in "Jenny don't change your number 8675309".

When you plant the text offscreen via CSS, it's still copied to the clipboard when the user does a copy operation. You're essentially picking and choosing what gets copied, which can be very valuable if you expect users to copy your content.

Recent Features

  • By
    Send Text Messages with PHP

    Kids these days, I tell ya.  All they care about is the technology.  The video games.  The bottled water.  Oh, and the texting, always the texting.  Back in my day, all we had was...OK, I had all of these things too.  But I still don't get...

  • By
    9 Mind-Blowing WebGL Demos

    As much as developers now loathe Flash, we're still playing a bit of catch up to natively duplicate the animation capabilities that Adobe's old technology provided us.  Of course we have canvas, an awesome technology, one which I highlighted 9 mind-blowing demos.  Another technology available...

Incredible Demos

  • By
    Create Digg URLs Using PHP

    Digg recently came out with a sweet new feature that allows users to create Tiny Digg URLs which show a Digg banner at the top allowing easy access to vote for the article from the page. While I love visiting Digg every once in a...

  • By
    Scrolling &#8220;Agree to Terms&#8221; Component with MooTools ScrollSpy

    Remember the good old days of Windows applications forcing you to scroll down to the bottom of the "terms and conditions" pane, theoretically in an effort ensure that you actually read them? You're saying "No David, don't do it." Too late -- I've done...

Discussion

  1. Charlie

    Very nice, gotta love those little CSS tweaks.
    Small caveat, only works if the user double-clicks on line to select, won’t if it’s a “click-hold on first letter and drag cursor” kind of copy

  2. Does it work in all browsers? It’s very easy to use and simple, but I’m concerned that it could be too simple to work in every browser.

  3. These simple and small tweaks help a long way in designing. Thanks a lot for sharing :)

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!