remark-imgattr
v1.1.1
Published
add attributes to markdown and mdx images like (attribute: value)
Maintainers
Readme
Remark Image Attributes
Remark plugin to add attributes to markdown and mdx images
Adds attributes to images by extending the default syntax like (attribute1: value, attribute2: value). Attributes are applied to the image's hProperties, enabling framework component props in Astro and other unified pipelines.
[!NOTE] If using remark-unwrap-images run this plugin first
Syntax
(key: value, key: value, ...)Attributes are a comma-separated list of key: value pairs in a second set of parentheses after the image.
| Value type | Example | Notes |
|---|---|---|
| String | class: hero | No quotes needed for simple strings |
| Number | width: 300 | Integers and decimals supported |
| Boolean | defer: true | Passed as a boolean to hProperties |
| Quoted string | title: "my photo" | " ' " ' all supported; backslash escape with \ |
| CSS value | style: border: 1px solid red; | Colons in values are fine |
| Array | widths: [300, 600, 900] | Parsed as a JS array |
| Nested object | data: (x: 100, y: 200) | Parsed as a JS object |
| JSON object | metadata: {"key": "val"} | Parsed as a JS object |
Quoting
Commas inside [] arrays and () nested structures are handled automatically. Plain string values that contain commas must be quoted, otherwise the value will be silently truncated at the first comma:
<!-- correct: quoted string value containing a comma -->
(sizes: "(min-width: 600px) 600w, 300w")
<!-- correct: commas inside [] are fine without quotes -->
(widths: [300, 600, 900])Usage in Astro
import { defineConfig } from 'astro/config';
import imgAttr from 'remark-imgattr';
// https://astro.build/config
export default defineConfig({
markdown: {
remarkPlugins:[imgAttr]
}
});Setting default attributes
You can pass default attributes that will apply to all markdown and mdx images:
import { defineConfig } from 'astro/config';
import imgAttr from 'remark-imgattr';
// https://astro.build/config
export default defineConfig({
markdown: {
remarkPlugins:[
[imgAttr, { defaults: { width: 700, format: 'avif' } }],
],
},
});If an image specifies the same attributes as defaults, the image's value for that attribute will be used instead of the default value.
Example
(style: border: 1px solid #ccc; padding: 10px;, width: 100)
(width: 300, height: 150)Support for Astro Specific Syntax
(width: 300, widths: [300, 600], sizes: "(min-width: 600px) 600w, 300w")
(quality: 100, format: avif)