Skip to content

Embed SVG exports

Every SVG you export from Molkit is a self-contained file. Its viewBox uses the coordinates of the Molkit canvas, so the numbers do not start at 0. It has a root id of the form molkit-xxxxx that is unique to each export. Its internal style block is scoped to that id with :where(#molkit-xxxxx) selectors, and it can carry data-mk-* chemistry metadata.

How you put the file on a page decides what you can do with it afterward. The two most common problems are duplicate ids and page CSS that leaks into the drawing; both are covered after the embedding methods and sizing.

If you have not exported anything yet, start with the SVG export reference and the developer overview.

index.html
<img src="/img/benzene.svg" alt="Benzene ring" width="320">

Use img for a static picture. The browser renders the SVG in an isolated context: scripts never run, your page CSS cannot reach inside, and your JavaScript cannot read the chemistry metadata or control animations. Most browsers still apply the dark-mode media query in theme-aware exports, so the figure still switches between light and dark.

To inline at build time, paste the file’s contents into your HTML, or use your site generator’s include mechanism (partials, shortcodes, or raw imports). The export is a single file with no external dependencies, so a verbatim include works.

To inline at runtime, fetch the file and insert it:

embed.js
async function embedMolkitSvg(url, target) {
const res = await fetch(url);
if (!res.ok) throw new Error(`Failed to load ${url}: ${res.status}`);
const text = await res.text();
const doc = new DOMParser().parseFromString(text, 'image/svg+xml');
const svg = doc.documentElement;
if (svg.nodeName !== 'svg') throw new Error(`${url} is not an SVG document`);
target.replaceChildren(svg);
return svg;
}
embedMolkitSvg('/img/benzene.svg', document.querySelector('.mk-embed'));

Inline SVG runs in your page’s context, including any script elements or event-handler attributes it contains. Inline only SVGs that you exported yourself or otherwise trust. If the file comes from users, sanitize it first or use img.

A fixed export has explicit width and height attributes (the content bounds times the export scale) and a viewBox. The Responsive (remove width/height) checkbox in the export dialog removes the two attributes and keeps the viewBox, so the SVG fills its container and keeps its aspect ratio.

To let a fixed export shrink on small screens:

embed.css
.mk-embed svg {
max-width: 100%;
height: auto;
}

To size a responsive export, set the size on its container. Match aspect-ratio to the third and fourth numbers of the viewBox (its width and height):

embed.css
.mk-figure {
max-width: 320px;
aspect-ratio: 92.5 / 100; /* viewBox width / height */
}
.mk-figure svg {
width: 100%;
height: 100%;
}

Put several copies of one export on a page

Section titled “Put several copies of one export on a page”

Each export gets fresh ids: the random molkit-xxxxx root id, and suffixed internal ids such as bond-grad-bond_..._0nyq30 on gradient definitions. Two different exports therefore never collide.

Animated exports work differently. Their ids come from the exported content, not from chance: the root id is molkit- followed by a short hash of the exported file, and every internal id starts with that same hash (for example 0k3j9az_mk_1). Exporting the same animation twice gives the same file, byte for byte, and so does running the same script again. Two animations that draw different content never collide on one page. Identical content gives identical ids, whichever animation it came from: a duplicated animation, or one script run in two documents, shares every id with the original, so the steps below apply to those copies too.

If you inline the same file twice, every id appears twice in one document, and the second copy renders wrongly:

  1. Gradient, clip-path, and mask definitions are referenced by url(#id). The browser resolves a duplicated id to the first match in the document, so the second copy uses the first copy’s definitions.
  2. Bond gradients use gradientUnits="userSpaceOnUse" with absolute coordinates. When the two copies sit at different positions, the second copy’s gradient strokes can render shifted, solid, or invisible.
  3. The internal style block is scoped with :where(#molkit-xxxxx) selectors, so renaming ids must also update the style text, or the second copy loses its styling.

To fix this, add a suffix to every id in each inlined copy and rewrite all three kinds of reference:

dedup.js
function dedupMolkitIds(svg, suffix) {
const idMap = new Map();
for (const el of svg.querySelectorAll('[id]')) {
const next = el.id + suffix;
idMap.set(el.id, next);
el.id = next;
}
const rewriteUrls = (text) =>
text.replace(/url\(["']?#([^"')]+)["']?\)/g,
(m, id) => (idMap.has(id) ? `url(#${idMap.get(id)})` : m));
for (const el of svg.querySelectorAll('*')) {
for (const attr of [...el.attributes]) {
if (attr.value.includes('url(#')) attr.value = rewriteUrls(attr.value);
if (/^(xlink:)?href$/.test(attr.name) && attr.value.startsWith('#')) {
const id = attr.value.slice(1);
if (idMap.has(id)) attr.value = '#' + idMap.get(id);
}
}
}
for (const style of svg.querySelectorAll('style')) {
style.textContent = rewriteUrls(style.textContent)
.replace(/#([A-Za-z][\w-]*)/g,
(m, id) => (idMap.has(id) ? '#' + idMap.get(id) : m));
}
return svg;
}
// One unique suffix per inlined copy:
dedupMolkitIds(svgEl, '-' + Math.random().toString(36).slice(2, 8));

Hex colors in the style text (#ffffff) are left unchanged because they are not in the id map. If you control the exports, there is a simpler alternative: export the drawing once for each place it appears. Each export gets its own ids.

Inline SVG text inherits typographic properties from the host page. A site-wide line-height: 1.7 or letter-spacing: 0.02em moves atom labels and formula subscripts out of position, because the export was laid out with the browser defaults. Reset them on the wrapper:

embed.css
.mk-embed,
.mk-embed text,
.mk-embed tspan {
line-height: normal;
letter-spacing: normal;
word-spacing: normal;
text-transform: none;
}

Put the same wrapper div with a known class around every embed. It gives you a sizing hook, a reset boundary, and a stable selector for theming overrides and the cookbook recipes.

The Electrostatic maps option in the export dialog puts a map inside the SVG or in a separate .esp file. The SVG refers to a separate file by a relative path, esp/<name>-<fingerprint>.esp by default, so publish the file at that path next to the SVG. The browser saves the download without the folder; the export message names the folder to put it in. Only the Molkit Viewer reads the file, when a reader turns the map on; the SVG looks the same with or without it.

When you inline the SVG, a relative path resolves against the page instead of the SVG. To keep the path working, mount the figure with the viewer’s src option, which remembers the SVG’s address. Alternatively, keep all map files in one folder and set MolkitWidget.espBase to it.