Alpine Portal
Screen-size-responsive, bidirectional DOM teleportation for Alpine.js v3.
Move elements between containers based on CSS media queries and restore them automatically.
ð Introduction
Alpine's built-in x-teleport directive moves elements unconditionally to another part of the DOM.
However, real-world responsive design often requires an element (such as a search bar, navigation links, or action button)
to live in one container on mobile (e.g. inside a drawer) and inside a completely different layout container on desktop (e.g. the header bar).
Alpine Portal provides the x-portal directive to solve this natively:
- ð Media Query Driven: Evaluated by the browser's native CSS engine via
window.matchMedia. - ð Order-Preserving Bidirectional: Automatically returns elements to their exact original sibling slot when the viewport changes.
- ðŊ Multi-Target Routing: Jump between multiple container targets across various screen sizes.
- ðĄïļ Layout Shift Free: Optional
.spacerprevents Cumulative Layout Shift (CLS). - ðŠķ Zero Dependencies: Lightweight pure vanilla JS (under 2KB gzipped).
ðĶ Installation
Via CDN
Include Alpine Portal before loading Alpine.js:
<!-- Alpine Portal v1.0.0 -->
<script src="https://cdn.jsdelivr.net/gh/nabeghe/alpine-portal@v1.0.0/dist/alpine-portal.min.js" defer></script>
<!-- Alpine.js v3 -->
<script defer src="https://cdn.jsdelivr.net/npm/alpinejs@3.x.x/dist/cdn.min.js"></script>
Via NPM
npm install alpine-portal
Register the plugin with Alpine:
import Alpine from 'alpinejs';
import Portal from 'alpine-portal';
// Standard registration
Alpine.plugin(Portal);
// Or with custom screen breakpoints
Alpine.plugin(Portal, {
screens: {
tablet: 800,
desktop: 1280,
}
});
window.Alpine = Alpine;
Alpine.start();
⥠Quick Start
Attach x-portal and a breakpoint condition to any element:
<!-- Source Container (Mobile) -->
<div id="mobile-drawer">
<div x-portal="#desktop-header" x-portal:screen="768">
<input type="search" placeholder="Search...">
</div>
</div>
<!-- Target Container (Desktop) -->
<header id="desktop-header">
<!-- Search input teleports here when viewport âĨ 768px -->
</header>
ð Core Mechanics
Exact Sibling Order Preservation
In earlier versions or naive implementations, returning an element uses appendChild(),
which forces the element to the bottom of its original parent, permanently corrupting sibling layout order.
In Alpine Portal v1.0.0, an invisible DOM Anchor Comment node (<!-- x-portal-anchor -->)
is placed immediately before the element upon initialization. When the element reverts, it returns
precisely into its original sibling slot:
<div id="parent">
<span>Item 1</span>
<!-- Item 2 teleports to #target, but returns right between Item 1 and Item 3! -->
<div x-portal="#target" x-portal:screen.md>Item 2</div>
<span>Item 3</span>
</div>
Preventing Cumulative Layout Shift (CLS) with .spacer
When an element teleports away from its original container, the remaining content may abruptly collapse upward, triggering an unpleasant Cumulative Layout Shift (CLS).
Add the .spacer (or .placeholder) modifier. Alpine Portal leaves a matching placeholder
element retaining the original element's computed width and height until it returns:
<!-- Leaves an invisible dimension-matched spacer in place -->
<div x-portal.spacer="#target" x-portal:screen="768">
Fixed Height Hero Widget
</div>
ð Breakpoint Syntax
The x-portal:screen directive supports numbers, named breakpoints, and ranges:
| Syntax | Generated Media Query | Teleportation Behavior |
|---|---|---|
x-portal:screen="640" |
(min-width: 640px) |
Teleports when viewport âĨ 640px |
x-portal:screen="-640" |
(max-width: 640px) |
Teleports when viewport âĪ 640px |
x-portal:screen.md |
(min-width: 768px) |
Tailwind named screen alias (modifier syntax) |
x-portal:screen="'-md'" |
(max-width: 768px) |
Negative named screen alias |
x-portal:screen="'640-1024'" |
(min-width: 640px) and (max-width: 1024px) |
Active strictly within range query |
x-portal:screen="0" |
None | Disables teleportation |
Tailwind Preset Breakpoints
The following presets are built-in:
sm: 640pxmd: 768pxlg: 1024pxxl: 1280px2xl: 1536px
Arbitrary Media Queries (x-portal:media)
For custom conditions (orientation, aspect ratio, dark mode, pointer capabilities), use x-portal:media:
<!-- Teleport in landscape mode -->
<div x-portal="#sidebar" x-portal:media="(orientation: landscape)"></div>
<!-- Teleport on touch-screen devices -->
<div x-portal="#touch-menu" x-portal:media="(pointer: coarse)"></div>
ð§Đ Placement Modifiers
Control where the element lands inside or relative to the destination selector:
| Modifier | DOM Action | Description |
|---|---|---|
.prepend |
target.prepend(el) |
Inserts as the first child of target |
.append |
target.appendChild(el) |
Inserts as the last child of target (default) |
.before |
target.before(el) |
Inserts immediately before target element |
.after |
target.after(el) |
Inserts immediately after target element |
<!-- Prepend to the top of the header -->
<div x-portal.prepend="#header-bar" x-portal:screen="768">Alert Banner</div>
ðŊ Multi-Target Responsive Routing
Often an element must travel between more than two containers. Pass a dictionary of
{ 'breakpoint': 'target' } routes:
<div x-portal="{
'-640': '#mobile-drawer',
'641-1024': '#tablet-toolbar',
'1025': '#desktop-sidebar'
}">
Multi-Target Navigation Links
</div>
âïļ State-Driven Teleportation (when)
Control teleportation reactively with Alpine data attributes using x-portal:when:
<div x-data="{ isModalOpen: false }">
<button @click="isModalOpen = !isModalOpen">Toggle Search</button>
<!-- Teleports to modal ONLY when isModalOpen is true AND viewport is mobile -->
<div x-portal="#modal-body" x-portal:screen="-768" x-portal:when="isModalOpen">
Search Bar
</div>
</div>
ðĄ Lifecycle Events
Alpine Portal dispatches bubbling custom events on the portal element:
| Event | Trigger | $event.detail Properties |
|---|---|---|
portal:teleport |
Fired when element moves to target | { target, targetElement, placement, portal } |
portal:revert |
Fired when element returns to original position | { originalParent, portal } |
<div x-portal="#target"
x-portal:screen="640"
@portal:teleport="console.log('Moved to: ', $event.detail.target)"
@portal:revert="console.log('Returned back home!')">
Interactive Element
</div>
⥠Livewire & Teardown
Laravel Livewire: Alpine Portal automatically listens to livewire:navigating
and unbinds all media query listeners before SPA navigation occurs.
Alpine v3 Cleanup: When an element is destroyed (e.g. by x-if or component teardown),
Alpine Portal connects to Alpine's official cleanup() hook to automatically destroy listeners,
remove anchors, and prevent memory leaks.
ðŪ Live Interactive Playground
Try testing responsive teleportation directly inside this documentation page:
ð Directive Cheat Sheet
| Directive / Modifier | Description |
|---|---|
x-portal="#target" | Teleports element to specified CSS selector |
x-portal="{ '-640': '#m', '641': '#d' }" | Multi-target routing map |
x-portal.prepend | Prepends as first child inside destination |
x-portal.append | Appends as last child inside destination (default) |
x-portal.before | Inserts immediately before target element |
x-portal.after | Inserts immediately after target element |
x-portal.spacer | Inserts invisible dimension spacer to eliminate CLS |
x-portal:screen="640" | Min-width breakpoint in pixels |
x-portal:screen="-640" | Max-width breakpoint in pixels |
x-portal:screen.md | Tailwind named breakpoint shortcut |
x-portal:screen="'640-1024'" | Range query breakpoint |
x-portal:media="query" | Arbitrary media query string |
x-portal:when="condition" | Alpine reactive condition |
@portal:teleport | Fired on teleportation to target |
@portal:revert | Fired on return to original parent |