Skip to content
Go back

Using Custom Remark Plugins in an Astro Project

Published:  at  05:00 PM
Reads: 0 Document cards passing through a transformation node to become colored callouts and button components.

This article introduces how to use two custom Remark plugins — remark-admonitions (callout boxes) and remark-button (buttons) — in a new Astro project, enabling Markdown content to support rich custom components.

Of course, I know there are plenty of ready-made plugins available online, but I chose this approach anyway.

Preview

Before installation, let’s first see what these two plugins can achieve.

Admonitions (Callout Boxes)

Five types of admonitions are suitable for different scenarios:

This is a regular note admonition, used for supplementary information.

This is a friendly tip, great for sharing small tricks.

This is an info admonition, used for providing extra information.

This is a warning admonition, used to alert users.

This is a danger warning, used to remind users to proceed with caution.

Button

Here are various button variants:

Small Primary Button

Medium Success Button

Large Danger Button

Warning Button

Custom Purple Rounded Button

Plugin Overview

These two plugins are built on remark-directive and use Markdown’s ::: directive syntax to insert custom UI components into articles.

Prerequisites

Before getting started, make sure your project meets the following requirements:

npm packages to install:

PackagePurpose
remark-directiveParses the ::: directive syntax in Markdown
unist-util-visitTraverses and manipulates AST nodes
hastscriptCreates hast (HTML AST) nodes declaratively
pnpm add remark-directive unist-util-visit hastscript

Step 1: Create Plugin Files

Create a plugins/ directory in the project root and place the following two files inside.

remark-admonitions.ts

import { visit } from "unist-util-visit";
import { h } from "hastscript";

const admonitions = ["note", "tip", "info", "warning", "danger"];

export default function remarkAdmonitions() {
  return tree => {
    visit(tree, node => {
      if (
        node.type === "containerDirective" ||
        node.type === "leafDirective" ||
        node.type === "textDirective"
      ) {
        if (admonitions.includes(node.name)) {
          const data = node.data || (node.data = {});
          const hast = h("div", node.attributes || {});

          if (node.children && node.children.length > 0) {
            const firstChild = node.children[0];
            if (firstChild.type === "paragraph") {
              const firstChildData = firstChild.data || (firstChild.data = {});
              const existingClass =
                (firstChildData.hProperties?.className as string[]) || [];
              firstChildData.hProperties = {
                ...firstChildData.hProperties,
                className: ["admonition-title", ...existingClass],
              };
            }
          }

          data.hName = hast.tagName;
          data.hProperties = {
            ...hast.properties,
            className: [
              node.name,
              ...((hast.properties?.className as string[]) || []),
            ],
          };
        }
      }
    });
  };
}

remark-button.ts

import { h } from "hastscript";
import type { Root } from "mdast";
import { visit } from "unist-util-visit";

const PRESET_SIZES = ["xs", "sm", "md", "lg", "xl"];
const PRESET_COLORS = [
  "primary",
  "secondary",
  "success",
  "danger",
  "warning",
  "info",
  "light",
  "dark",
  "pink",
  "purple",
  "indigo",
  "teal",
  "cyan",
  "orange",
];
const PRESET_TEXT_COLORS = ["white", "black", "gray", "light", "dark"];

export default function remarkButton() {
  return (tree: Root) => {
    visit(tree, node => {
      if (
        node.type !== "containerDirective" &&
        node.type !== "leafDirective" &&
        node.type !== "textDirective"
      ) {
        return;
      }

      if (node.name !== "button") return;

      const data = node.data || (node.data = {});
      const {
        color,
        textColor,
        size,
        padding,
        borderRadius,
        class: className,
        target,
        ...linkAttributes
      } = node.attributes ?? {};

      const hast = h("a", {
        ...linkAttributes,
        ...(className ? { class: className } : {}),
      });
      const classNames = [
        "custom-button",
        ...((hast.properties?.className as string[]) || []),
      ];
      const inlineStyles: string[] = [];

      if (size) {
        if (PRESET_SIZES.includes(size)) {
          classNames.push(`button-${size}`);
        } else {
          inlineStyles.push(`--button-font-size: ${size}`);
        }
      }

      if (color) {
        if (PRESET_COLORS.includes(color)) {
          classNames.push(`button-${color}`);
        } else {
          classNames.push("button-custom-color");
          inlineStyles.push(`--button-color: ${color}`);
        }
      }

      if (textColor) {
        if (PRESET_TEXT_COLORS.includes(textColor)) {
          classNames.push(`button-text-${textColor}`);
        } else {
          inlineStyles.push(`--button-contrast: ${textColor}`);
        }
      }

      if (padding) inlineStyles.push(`--button-padding: ${padding}`);
      if (borderRadius) {
        inlineStyles.push(`--button-radius: ${borderRadius}`);
      }

      const properties: Record<string, string | string[]> = {
        ...hast.properties,
        className: classNames,
        target: target || "_blank",
        rel: "noopener noreferrer nofollow",
      };

      if (inlineStyles.length > 0) {
        properties.style = inlineStyles.join("; ");
      }

      data.hName = "a";
      data.hProperties = properties;
    });
  };
}

Step 2: Configure Astro

Edit astro.config.ts and register these two plugins in markdown.remarkPlugins:

import { defineConfig } from "astro/config";
import remarkDirective from "remark-directive";
import remarkAdmonitions from "./plugins/remark-admonitions";
import remarkButton from "./plugins/remark-button";

export default defineConfig({
  markdown: {
    remarkPlugins: [
      remarkDirective, // Must be registered before custom plugins
      remarkAdmonitions,
      remarkButton,
    ],
  },
});

remarkDirective must come before remarkAdmonitions and remarkButton. This is because remark-directive is responsible for parsing the ::: syntax into directive nodes, and then the custom plugins convert these nodes into HTML. If the order is wrong, the custom plugins won’t receive any directive nodes, and all ::: blocks won’t be rendered.

Step 3: Add CSS Styles

Admonition Styles

In your global CSS file (e.g., src/styles/global.css), add:

/* Admonition base styles */
.prose .note,
.prose .tip,
.prose .info,
.prose .warning,
.prose .danger {
  @apply my-4 rounded-lg border-l-4 p-4;
}

/* Admonition title */
.prose .note .admonition-title,
.prose .tip .admonition-title,
.prose .info .admonition-title,
.prose .warning .admonition-title,
.prose .danger .admonition-title {
  @apply mb-2 text-lg font-bold;
}

/* Color schemes by type */
.prose .note {
  @apply border-blue-500 bg-blue-50 text-blue-900;
}

.prose .tip {
  @apply border-green-500 bg-green-50 text-green-900;
}

.prose .info {
  @apply border-cyan-500 bg-cyan-50 text-cyan-900;
}

.prose .warning {
  @apply border-yellow-500 bg-yellow-50 text-yellow-900;
}

.prose .danger {
  @apply border-red-500 bg-red-50 text-red-900;
}

/* Dark mode adaptation */
html[data-theme="dark"] .prose .note {
  @apply border-blue-400 bg-blue-950/50 text-blue-100;
}

html[data-theme="dark"] .prose .tip {
  @apply border-green-400 bg-green-950/50 text-green-100;
}

html[data-theme="dark"] .prose .info {
  @apply border-cyan-400 bg-cyan-950/50 text-cyan-100;
}

html[data-theme="dark"] .prose .warning {
  @apply border-yellow-400 bg-yellow-950/50 text-yellow-100;
}

html[data-theme="dark"] .prose .danger {
  @apply border-red-400 bg-red-950/50 text-red-100;
}

Button Styles

The button styles use CSS variables to control fill, border, shadow, sizing, and text contrast. Preset variants, theme switching, and custom attributes therefore share one visual language while retaining the site’s monospace typography and accent color.

/* ===== Markdown buttons (remark-button) ===== */
:root,
html[data-theme="light"] {
  --button-default-contrast: #fff;
}

html[data-theme="dark"] {
  --button-default-contrast: var(--background);
}

.custom-button {
  --button-color: var(--accent);
  --button-contrast: var(--button-default-contrast);
  --button-fill: var(--button-color);
  --button-fill-hover: color-mix(
    in srgb,
    var(--button-color) 88%,
    var(--foreground)
  );
  --button-border: var(--button-color);
  --button-padding: 0.55rem 0.95rem;
  --button-radius: 0.375rem;
  --button-font-size: 0.875rem;
  --button-gap: 0.65rem;
  --button-shadow: 3px;

  display: inline-flex;
  width: fit-content;
  max-width: 100%;
  align-items: center;
  justify-content: center;
  gap: var(--button-gap);
  margin-block: 0.75rem;
  padding: var(--button-padding);
  border: 1px solid var(--button-border);
  border-radius: var(--button-radius);
  background-color: var(--button-fill);
  box-shadow: var(--button-shadow) var(--button-shadow) 0
    color-mix(in srgb, var(--button-color) 22%, transparent);
  color: var(--button-contrast);
  font-size: var(--button-font-size);
  font-weight: 600;
  line-height: 1.35;
  letter-spacing: 0.01em;
  text-align: start;
  text-decoration: none;
  vertical-align: middle;
  transition:
    background-color 160ms ease,
    box-shadow 160ms ease,
    color 160ms ease,
    transform 160ms ease;
}

.custom-button::after {
  content: "↗";
  flex: none;
  font-size: 1.05em;
  font-weight: 400;
  line-height: 1;
  opacity: 0.82;
  transition: transform 160ms ease;
}

.custom-button[target="_self"]::after {
  content: "→";
}

.custom-button > p {
  margin: 0;
}

.custom-button:hover {
  background-color: var(--button-fill-hover);
  box-shadow: 1px 1px 0 color-mix(in srgb, var(--button-color) 30%, transparent);
  color: var(--button-contrast);
  text-decoration: none;
  transform: translate(1px, 1px);
}

.custom-button:hover::after {
  transform: translate(1px, -1px);
}

.custom-button:active {
  box-shadow: 0 0 0 transparent;
  transform: translate(2px, 2px);
}

.custom-button:focus-visible {
  outline: 2px dashed var(--button-color);
  outline-offset: 3px;
  text-decoration: none;
}

/* Keep the Markdown link styles from overriding the button treatment. */
.prose a.custom-button {
  color: var(--button-contrast);
  text-decoration: none;
}

.prose a.custom-button:hover {
  color: var(--button-contrast);
}

.button-xs {
  --button-padding: 0.25rem 0.6rem;
  --button-font-size: 0.75rem;
  --button-gap: 0.4rem;
  --button-shadow: 2px;
}

.button-sm {
  --button-padding: 0.4rem 0.75rem;
  --button-font-size: 0.8125rem;
  --button-gap: 0.5rem;
  --button-shadow: 2px;
}

.button-md {
  --button-padding: 0.55rem 0.95rem;
  --button-font-size: 0.875rem;
}

.button-lg {
  --button-padding: 0.7rem 1.1rem;
  --button-font-size: 1rem;
  --button-gap: 0.75rem;
}

.button-xl {
  --button-padding: 0.85rem 1.3rem;
  --button-font-size: 1.125rem;
  --button-gap: 0.85rem;
  --button-shadow: 4px;
}

.button-primary {
  --button-color: var(--accent);
  --button-contrast: var(--button-default-contrast);
}

.button-custom-color {
  --button-contrast: color-mix(
    in srgb,
    var(--button-color) 68%,
    var(--foreground)
  );
  --button-fill: color-mix(in srgb, var(--button-color) 17%, var(--background));
  --button-fill-hover: color-mix(
    in srgb,
    var(--button-color) 30%,
    var(--background)
  );
  --button-border: color-mix(in srgb, var(--button-color) 58%, var(--border));
}

.button-secondary {
  --button-color: var(--foreground);
  --button-contrast: var(--background);
}

.button-success {
  --button-color: #287a54;
  --button-contrast: #f7fffb;
}

.button-danger {
  --button-color: #b83b3b;
  --button-contrast: #fff8f8;
}

.button-warning {
  --button-color: #e7b73d;
  --button-contrast: #241b04;
}

.button-info {
  --button-color: #257c91;
  --button-contrast: #f4fdff;
}

.button-light {
  --button-color: #e8e8e8;
  --button-contrast: #282728;
}

.button-dark {
  --button-color: #282728;
  --button-contrast: #fdfdfd;
}

.button-pink {
  --button-color: #be185d;
  --button-contrast: #fff7fb;
}

.button-purple {
  --button-color: #6d28d9;
  --button-contrast: #fbf8ff;
}

.button-indigo {
  --button-color: #4338ca;
  --button-contrast: #f8f8ff;
}

.button-teal {
  --button-color: #0f766e;
  --button-contrast: #f3fffd;
}

.button-cyan {
  --button-color: #0e7490;
  --button-contrast: #f2fdff;
}

.button-orange {
  --button-color: #c2410c;
  --button-contrast: #fff8f4;
}

html[data-theme="dark"] .button-success {
  --button-color: #78d6a8;
  --button-contrast: #10231a;
}

html[data-theme="dark"] .button-danger {
  --button-color: #ff938b;
  --button-contrast: #2d1110;
}

html[data-theme="dark"] .button-warning {
  --button-color: #ffd166;
  --button-contrast: #2a2108;
}

html[data-theme="dark"] .button-info {
  --button-color: #69c7dc;
  --button-contrast: #0c252b;
}

html[data-theme="dark"] .button-light {
  --button-color: #e7e9ee;
  --button-contrast: #232839;
}

html[data-theme="dark"] .button-dark {
  --button-color: #0f1420;
  --button-contrast: #f4f6fb;
}

html[data-theme="dark"] .button-pink {
  --button-color: #f9a8d4;
  --button-contrast: #2b0917;
}

html[data-theme="dark"] .button-purple {
  --button-color: #c4b5fd;
  --button-contrast: #1f0f42;
}

html[data-theme="dark"] .button-indigo {
  --button-color: #a5b4fc;
  --button-contrast: #17173a;
}

html[data-theme="dark"] .button-teal {
  --button-color: #5eead4;
  --button-contrast: #0b2421;
}

html[data-theme="dark"] .button-cyan {
  --button-color: #67e8f9;
  --button-contrast: #0a272d;
}

html[data-theme="dark"] .button-orange {
  --button-color: #fdba74;
  --button-contrast: #2b1405;
}

.button-text-white {
  --button-contrast: #fff;
}

.button-text-black {
  --button-contrast: #000;
}

.button-text-gray {
  --button-contrast: #374151;
}

.button-text-light {
  --button-contrast: #f3f4f6;
}

.button-text-dark {
  --button-contrast: #111827;
}

@media (prefers-reduced-motion: reduce) {
  .custom-button,
  .custom-button::after {
    transition: none;
  }

  .custom-button:hover,
  .custom-button:active {
    transform: none;
  }
}

The button styles use native CSS and color-mix() and do not depend on Tailwind utility classes. They only require theme variables such as --background, --foreground, --accent, and --border. Custom colors are converted into a subdued tinted fill instead of a saturated block of color.

Step 4: Using in Markdown

Admonition Syntax

Supports five types: note, tip, info, warning, danger. The first paragraph inside an admonition is automatically rendered as a bold title.

:::note
This is a regular note admonition.
:::

:::tip
This is a friendly tip.
:::

:::info
This is an info admonition, used for providing extra information.
:::

:::warning
This is a warning admonition, used to alert users.
:::

:::danger
This is a danger warning, used to remind users to proceed with caution.
:::

Button Syntax

Buttons use the :::button{attributes...} syntax and support the following attributes:

AttributeDescriptionPreset ValuesCustom Example
hrefButton link URLAny URLhref="https://example.com"
sizeButton sizexs, sm, md, lg, xlsize="1.5rem"
colorPrimary/semantic toneprimary, secondary, success, danger, warning, info, light, dark, pink, purple, indigo, teal, cyan, orangecolor="#ff6b6b"
textColorText colorwhite, black, gray, light, darktextColor="#2d3436"
paddingPaddingAny CSS valuepadding="1rem 2rem"
borderRadiusBorder radiusAny CSS valueborderRadius="50px"
targetLink open modeDefault _blanktarget="_self"

When size, color, and textColor use preset values, corresponding CSS class names are generated. Non-preset values are written as CSS variables such as --button-font-size, --button-color, and --button-contrast, and the shared styles determine the final appearance. padding and borderRadius map to --button-padding and --button-radius respectively.

Preset Sizes

:::button{href="https://example.com" size="xs"}
Extra Small Button
:::

:::button{href="https://example.com" size="sm"}
Small Button
:::

:::button{href="https://example.com" size="md"}
Medium Button
:::

:::button{href="https://example.com" size="lg"}
Large Button
:::

:::button{href="https://example.com" size="xl"}
Extra Large Button
:::

Preset Colors

:::button{href="https://example.com" color="primary"}
Primary Button
:::

:::button{href="https://example.com" color="danger"}
Danger Button
:::

:::button{href="https://example.com" color="warning" textColor="black"}
Warning Button (Dark Text)
:::

Fully Custom

:::button{href="https://example.com" size="0.75rem"}
Extra Small Font Button
:::

:::button{href="https://example.com" color="#ff6b6b"}
Custom Red Button
:::

:::button{href="https://example.com" color="#ffeaa7" textColor="#2d3436"}
Custom Yellow Button with Dark Text
:::

:::button{href="https://example.com" padding="1rem 2rem"}
Custom Padding Button
:::

:::button{href="https://example.com" borderRadius="2rem"}
Rounded Button
:::

Combined Usage

:::button{href="https://example.com" size="lg" color="success"}
Large Success Button
:::

:::button{href="https://example.com" size="sm" color="danger"}
Small Danger Button
:::

:::button{href="https://example.com" color="#fd79a8" padding="1.5rem 3rem" borderRadius="50px"}
Fully Custom Button
:::

Additional Notes

Plugin Registration Order

The processing flow is as follows:

  1. remark-directive parses the :::name{...} syntax into directive AST nodes
  2. remark-admonitions / remark-button convert matching directive nodes into HTML

About TypeScript

If you use astro check for type checking, you may need to add type declarations for the plugin files. It’s recommended to create corresponding declaration files in the plugins/ directory:

// plugins/remark-admonitions.d.ts
declare module "./plugins/remark-admonitions" {
  const value: () => (tree: any) => void;
  export default value;
}

// plugins/remark-button.d.ts
declare module "./plugins/remark-button" {
  const value: () => (tree: any) => void;
  export default value;
}

CSS Framework Compatibility

Known Limitations

  1. Buttons open in a new tab by default (target="_blank"). To navigate in the current page, specify target="_self"
  2. The button’s rel attribute is fixed to "noopener noreferrer nofollow" and cannot be customized
  3. The first paragraph of an admonition is always rendered as a title and cannot be disabled
  4. Admonitions currently do not support passing custom attributes; only the five preset types are supported

Share this post on:

Previous Post
Tried Integrating an Online Gaming Platform
Next Post
Complete Guide to Free Website Building Resources