Here is a PLAIN, non-JavaScripted, HTML solution that is very simple to use, and superior to using <pre>
and <code>
elements, or heavy-handed JavaScript solutions which are always overkill. I have been using this trick for 20 years! It works in all browsers, old and new. Kids today have just failed to learn the old ways.
It allows your users to cut-and-paste code samples quickly. It also allows you to drop you code into an HTML element quickly, hassle-free, without having to escape all the <
and >
characters you normally have to do when using <code>
.
Use the <textarea>
element to share code, like so:
<textarea class="code" contenteditable="true" spellcheck="false" aria-label='Code Sample'>
My Sample Bookmark:
<a href="#bookmark1" id="b1" title="View my bookmark" target="_blank" rel="noreferrer nofollow noopener" accesskey="a" tabindex="0" aria-label="Bookmark">Got to My Bookmark</a>
</textarea>
...with some simple CSS styling...
<style>
textarea.code {
display: block;
width: 90%;
min-height: 5em;
overflow-y: auto;
overflow-x: hidden;
font-family: monospace;
border: 1px solid #bbb;
padding: 1em;
white-space:pre-wrap;
}
</style>
Notice that it looks like regular monospace <code>
but is block-level, honors text formats like <pre>
, long text now wraps, the code box size is controllable, and allows more flexible displays of large HTML or script blocks users can more easily access.
BTW....you can still use <pre><code>
. I still do for smaller examples. And don't worry about semantic or accessibility issues using <textarea>
as it is a replaced element and has a more versatile use. If you are worried, then simply add an ARIA label to your <textarea>
, like I have done above.
<pre>
and its behavior can be kept in mind as the word ”precisely” – snr