This tutorial is designed to guide developers on how to embed SVG images in HTML documents while ensuring that their internal text can be selected and searched by users. The article will detail two core methods: using inline SVG code directly and passing `
SVG (Scalable Vector Graphics) plays an important role in modern web design due to its vector nature and the advantage of staying legible at different resolutions. However, when SVG is embedded via the traditional tag, the SVG file is often viewed by browsers as a flat image, and the text content within it loses its selectable and searchable characteristics, which is a limitation in terms of user experience and content accessibility. In order to solve this problem, this article will introduce two effective methods to ensure that text in SVG can interact like ordinary HTML text.
Method 1: Inline SVG (Inline SVG)
Inline SVG is a way of embedding SVG code directly into an HTML document. With this approach, the SVG's XML structure becomes part of the HTML DOM. This means that all elements inside the SVG, including text defined by or tags, will exist as recognized DOM nodes. Therefore, this text can be selected by the browser, copied, searched via Ctrl F, and even manipulated via CSS and JavaScript.
Implementation steps:
Open the SVG file and copy its
Paste the copied code directly into the HTML document where you want the SVG to appear.
Sample code:
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Inline SVG example</title>
<h1>Inline SVG text optional presentation</h1>
<p>The text in the following SVG images can be selected and copied with the mouse:</p>
<svg width="453px" height="136px" viewbox="0 0 1000 300">
<defs>
<path id="MyPath" d="M 100 125
C 150 125 250 175 300 175
C 350 175 450 125 500 125
C 550 125 650 175 700 175
C 750 175 850 125 900 125"></path>
</defs>
<use xlink:href="#MyPath" fill="none" stroke="red"></use>
<text font-family="Verdana" font-size="60" fill="blue" letter-spacing="2">
<textpath xlink:href="#MyPath">
Choose shame or get war
</textpath>
</text>
<rect x="1" y="1" width="998" height="298" fill="none" stroke="blue" stroke-width="2"></rect>
</svg>
<p>You can now try to select or search for the text "Choose shame or get war" in the SVG. </p>
advantage:
Text is fully selectable and searchable.
Various parts of the SVG can be controlled directly via CSS and JavaScript.
Reduce HTTP requests and increase loading speed (for small SVGs).
shortcoming:
Increases the size of HTML files, which may result in verbose HTML code for complex SVGs.
Cache management is not as convenient as external files.
Method 2: Use the
When you want to keep the HTML file clean, or the SVG file is large and needs to be reused in multiple pages, you can use the
Implementation steps:
Make sure your SVG files exist on the server as separate files.
Use the tag in the HTML document, specify the URL of the SVG file through the data attribute, and set the width and height attributes.
Sample code:
Let's say you have an SVG file called toap04.svg with the same content as the
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Object tag embedding SVG example</title>
<h1>Optional demonstration of embedded SVG text in Object tag</h1>
<p>The following text in SVG images embedded via the <code><object></object></code> tag can also be selected and searched:</p>
<object data="https://www.w3.org/TR/SVG11/images/text/toap04.svg" width="453" height="136"></object>
<p>Please try to select or search the text content in the SVG. </p>
advantage:
Keep your HTML code simple.
SVG files can be cached independently for easy reuse and management.
Text is also selectable and searchable.
Supports more complex interactions, such as communicating with embedded SVG documents via JavaScript.
shortcoming:
May introduce additional HTTP requests.
Directly manipulating elements inside an SVG via JavaScript is slightly more complex than inline SVG, typically requiring access to its DOM via the contentDocument property.
There may be differences in compatibility in some older browsers (although support is good in modern browsers).
Notes and Summary
Why doesn't the tag work? The tag treats SVG as an image resource, and browsers typically render it into a bitmap or flatten its internal structure so that its text content is no longer an interactive DOM element.
Which method to choose?
For small, one-time use SVGs that require a high degree of customization and direct JavaScript/CSS control, inline SVG is a better choice.
For large SVGs that need to be reused, keep the HTML structure clear, or want to take advantage of browser caching, the tag is a more suitable solution.
Accessibility: Ensuring that text in SVG is selectable and searchable is critical for screen readers, search engine optimization (SEO), and the general user experience. This makes SVG content more semantic and accessible.
By mastering the above two methods, developers can flexibly embed SVG images in HTML while taking full advantage of the interactivity of SVG text, thereby creating richer and more accessible web content.
The above is the detailed content of Embedding SVG images with selectable text in HTML: two practical methods. For more information, please follow other related articles on the PHP Chinese website!
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
When the first child element of a Flex container dynamically adjusts the font-size, the container will be vertically offset along the inline baseline; while a normal block-level container will change in height due to the linkage between line height and font measurement. The root cause lies in the baseline alignment mechanism of the Flex container. By default, the baseline of the first child is the container baseline. This can be completely solved through vertical-align: top or explicit baseline control.
This article explains in detail why transform: translate() combined with the keydown event cannot move elements, and provides a reliable solution based on CSS positioning and JavaScript, covering absolute positioning settings, coordinate update logic, code robustness optimization, and common pitfalls.
This article explains in detail how to safely and reliably dynamically switch chart types (line/bar/pie) in Chart.js, and solve the problem of Cannot read properties of undefined errors caused by mismatched data structures and rendering exceptions after type switching. The core lies in destroying old instances, deep copying configurations, and accurately rebuilding data structures by type.
This article explains in detail how to safely and efficiently extract user input from HTML forms and structure it into JavaScript objects as attribute parameters of analytics.track() to avoid hard coding and syntax errors and support flexible expansion.
This article explores why providing 2x images to high DPR devices may lower Lighthouse performance scores, and provides practical solutions to balance visual quality and real performance: including proper srcset configuration, image compression strategies, modern format selection, and load priority control.
This article explains in detail the root cause of style failure when applying custom CSS in the WordPress Divi theme builder. It provides practical solutions for improving selector specificity, accurately positioning elements, and rational use of !important, as well as debugging tips and code optimization examples.
This article introduces a complete solution for disabling the "Next" button when the form does not meet the conditions, and using native HTML5 form validation or JavaScript dynamic control to display a friendly prompt message when the disabled button is clicked.
This article introduces how to use jQuery to dynamically switch background images after button clicks, and corrects problems such as CSS selector misuse, inline event coupling, and logical redundancy in the original code, providing a concise and maintainable interaction solution.