How to Highlight Text in HTML: Simple Syntax and Examples
To highlight text in HTML, use the
<mark> tag which applies a yellow background by default. Alternatively, you can use CSS styles like background-color on any element to customize the highlight color.Syntax
The simplest way to highlight text is by wrapping it in the <mark> tag. This tag highlights text with a yellow background by default.
You can also use CSS to highlight text by applying the background-color property to any HTML element.
html
<mark>Highlighted text</mark>
<span style="background-color: yellow;">Highlighted text with CSS</span>Output
Highlighted text (with yellow background)
Highlighted text with CSS (with yellow background)
Example
This example shows how to highlight text using the <mark> tag and CSS styling with a custom color.
html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Highlight Text Example</title> <style> .custom-highlight { background-color: lightgreen; padding: 0 0.2rem; border-radius: 0.2rem; } </style> </head> <body> <p>This is a normal sentence with <mark>highlighted text</mark> using the mark tag.</p> <p>This is a sentence with <span class="custom-highlight">custom highlighted text</span> using CSS.</p> </body> </html>
Output
A webpage showing two paragraphs: one with yellow highlighted text using <mark>, and one with light green highlighted text using CSS styling.
Common Pitfalls
- Using the
<b>or<strong>tags to highlight text only changes font weight, not background color. - Applying
background-colorwithout padding can make the highlight look cramped. - For accessibility, ensure highlight colors have good contrast with text color.
html
<!-- Wrong: bold does not highlight -->
<p>This is <b>bold text</b>, not highlighted.</p>
<!-- Right: use mark or background-color -->
<p>This is <mark>highlighted text</mark>.</p>
<p>This is <span style="background-color: yellow; padding: 0 0.2rem;">highlighted text</span>.</p>Output
Paragraph showing bold text without highlight and paragraphs showing proper highlighted text with background color.
Quick Reference
Use the <mark> tag for simple highlights. Use CSS background-color for custom colors and styles. Always check color contrast for readability.
| Method | Description | Example |
|---|---|---|
| tag | Default yellow highlight | text |
| CSS background-color | Custom highlight color | text |
| CSS with padding | Better spacing around highlight | text |
Key Takeaways
Use the tag for quick and semantic text highlighting in HTML.
Apply CSS background-color for custom highlight colors and styles.
Add padding with CSS to make highlights look neat and readable.
Avoid using bold or strong tags alone for highlighting purposes.
Ensure highlight colors have good contrast for accessibility.