阿里云主机折上折
  • 微信号
Current Site:Index > The role and usage scenarios of the '<mark>' tag

The role and usage scenarios of the '<mark>' tag

Author:Chuan Chen 阅读数:61330人阅读 分类: HTML

The <mark> tag is a semantic element in HTML5 used to highlight specific parts of text. It is typically employed to identify content related to the user's current action or search keywords, visually appearing with a yellow background. Below is a detailed exploration of its purpose, use cases, and practical examples.

Basic Function of the <mark> Tag

The core function of <mark> is to highlight text fragments. Its default style is a yellow background (similar to a highlighter effect), but this can be customized via CSS. Unlike <strong> (indicating importance) or <em> (indicating emphasis), the semantics of <mark> lean more toward "relevance" rather than "importance."

<p>In search results, documents related to <mark>HTML5</mark> are highlighted.</p>

Typical Use Cases

1. Highlighting Search Keywords

In search engines or site search functionality, <mark> is commonly used to mark keywords matching user queries:

<!-- Search result example -->
<div class="search-result">
  <h3>HTML5 Features</h3>
  <p>...<mark>HTML5</mark> introduced <mark>semantic tags</mark> like header, footer...</p>
</div>

2. User Action Feedback

When users select text or interact, dynamically mark relevant content:

// Highlight user-selected text
document.addEventListener('selectionchange', () => {
  const selection = window.getSelection();
  if (selection.toString().trim()) {
    const range = selection.getRangeAt(0);
    const mark = document.createElement('mark');
    range.surroundContents(mark);
  }
});

3. Education/Annotation Systems

In online learning platforms or documentation systems, marking key content:

<blockquote>
  The CSS box model includes: margin, border, padding, and <mark>content</mark>.
  <footer>—Excerpt from "Web Development Basics"</footer>
</blockquote>

Style Customization

While the default style is yellow background with black text, it can be fully overridden with CSS:

mark {
  background-color: #ffeb3b; /* Default yellow */
  color: #333;
  padding: 0.2em;
}

/* Dark mode adaptation */
@media (prefers-color-scheme: dark) {
  mark {
    background-color: #fdd835;
    color: black;
  }
}

/* Custom theme */
mark.important {
  background: linear-gradient(to right, #ff4081, #ff9100);
  color: white;
}

Comparison with Other Tags

Tag Semantics Default Style Use Case
<mark> Relevance highlight Yellow background Search matches, dynamic marking
<strong> Importance emphasis Bold Critical data, warnings
<em> Tone emphasis Italic Emphasizing tone, foreign terms
<span> No semantics None Pure styling wrapper

Dynamic Content Handling Example

Implement real-time highlighting with JavaScript:

<input type="text" id="searchInput" placeholder="Enter keywords">
<article id="content">
  <p>HTML5 semantic tags include section, article, nav, etc.</p>
</article>

<script>
  document.getElementById('searchInput').addEventListener('input', (e) => {
    const text = e.target.value.trim();
    const content = document.getElementById('content');
    if (!text) {
      content.querySelectorAll('mark').forEach(m => m.replaceWith(m.textContent));
      return;
    }
    
    const regex = new RegExp(text, 'gi');
    content.innerHTML = content.innerHTML.replace(
      regex, 
      match => `<mark>${match}</mark>`
    );
  });
</script>

Accessibility Recommendations

  1. ARIA Attributes: For dynamically generated highlights, consider adding aria-live="polite":
    <mark aria-live="polite">HTML5</mark>
    
  2. Color Contrast: Ensure custom background and text colors meet WCAG 2.1 AA standards (at least 4.5:1).
  3. Keyboard Navigation: If highlighted content is interactive, support tabindex="0".

Browser Compatibility Notes

All modern browsers support <mark>, but note:

  • IE9+ supports it, but some older versions may require style resets.
  • Highlight backgrounds may not appear by default when printing; fix with CSS print styles:
    @media print {
      mark {
        background-color: yellow;
        color: black;
        -webkit-print-color-adjust: exact;
        print-color-adjust: exact;
      }
    }
    

Advanced Use: Code Syntax Highlighting

While specialized libraries are typically used, simple keyword marking can be achieved with <mark>:

<pre><code>
function <mark>add</mark>(a, b) {
  return a + <mark>b</mark>;
}
</code></pre>

<style>
  pre mark {
    background-color: rgba(255, 235, 59, 0.3);
    border-bottom: 1px dashed #ffc107;
  }
</style>

本站部分内容来自互联网,一切版权均归源网站或源作者所有。

如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn

Front End Chuan

Front End Chuan, Chen Chuan's Code Teahouse 🍵, specializing in exorcising all kinds of stubborn bugs 💻. Daily serving baldness-warning-level development insights 🛠️, with a bonus of one-liners that'll make you laugh for ten years 🐟. Occasionally drops pixel-perfect romance brewed in a coffee cup ☕.