CLS 0.56: A Mobile Menu Before Alpine Boots, and a Fix That Broke Buttons
A layout shift report tells us what moved, but not what pushed it. The element that moves and the element causing it are often different, and fixing the one that moved will not change a single digit.
1-minute summary
- Symptom / problem
- Lighthouse reports CLS 0.564 and points at the hero, but the real cause is a 425 px mobile menu using x-cloak
- Who should read
- Alpine.js site builders with high mobile CLS who fix the element that moves and see no change
- Fix in short
- x-cloak is only an attribute, so add a display none CSS rule in the head of the HTML and CLS drops to 0.008. Do not write an over-broad selector that makes the menu button unclickable.
I ran Lighthouse on a client's corporate website before handing it over and got CLS of 0.564, against a target below 0.1. The report pointed to the hero, so I spent quite a while adjusting it without changing the number. Once I found the actual cause, a single line of CSS fixed it. Then, that same day, I broke it again myself by adding another half-line of selector as a precaution. Menu buttons stopped working across the site.
I have removed or changed the domain name, color class names, and menu text. The measurements, sequence of events, and code that caused the problem are real.
The symptom: CLS 0.564, almost all from a single shift
The site is a multilingual corporate website built with Laravel, Tailwind, and Alpine.js. At the top is a nav bar with a logo and a hamburger button, followed by a hero with a full-screen video. On mobile, tapping the hamburger expands a menu below the nav bar. The menu contains 6 links and another 6 flags for choosing a language.
Lighthouse gave an overall CLS of 0.564. Looking at the details, the largest shift was 0.529 and happened once, at 637 ms after loading began. That meant the page was not making lots of small movements in different places. It was making one large jump just over half a second after someone first saw it.
For an actual user, this looks like the screen moving away from their finger. They are about to tap a button on the hero when the whole section jumps up by more than half a screen. A number above 0.5 is about more than just a score.
My first wrong guess: the report pointed to the hero, so I fixed the hero
The element reported as the source of the shift was the gradient overlay on the hero video, something like <div class="absolute inset-0 bg-gradient-to-b ...">, with its before and after positions.
{
"value": 0.529,
"time": 637,
"sources": [
{
"tag": "DIV",
"cls": "absolute inset-0 bg-gradient-to-b ...",
"from": { "y": 490, "height": 250 },
"to": { "y": 65, "height": 675 }
}
]
}
I read those two lines as: the height changed from 250 to 675, so the hero expanded during loading. I then jumped to the conclusion that the video's dimensions were initially unknown, and its box stretched once the metadata arrived. I went through and set dimensions on the video and its container. Measuring again gave exactly the same 0.564, down to the last digit.
My mistake was looking only at height and ignoring y. The y value changed from 490 to 65, meaning this box moved up by 425 px. As for the height that seemed to increase, adding the numbers shows that 490 + 250 and 65 + 675 both equal 740. The bottom edge stayed in the same place. Only the top edge changed.
The previousRect and currentRect values reported by the browser represent only the part of the element that is visible in the viewport. If the element is pushed below the bottom edge, the reported height includes only the part still visible. So 250 does not mean the hero used to be 250 tall. It means only 250 px of the hero was visible at that moment because something had pushed it down. Always look at y before height.
An observer that lets the browser report what moved and where
The numbers above did not come directly from the Lighthouse report page. I used PerformanceObserver to capture layout-shift entries and output the raw data, in a script that ran before the page loaded.
// ใส่ผ่าน page.addInitScript() ของ Playwright ให้รันก่อนสคริปต์ของหน้า
window.__shifts = [];
new PerformanceObserver(list => {
for (const e of list.getEntries()) {
if (e.hadRecentInput) continue; // shift ที่เกิดจากผู้ใช้กดเอง ไม่นับเป็น CLS
window.__shifts.push({
value: e.value,
time: Math.round(e.startTime),
sources: (e.sources || []).map(s => ({
tag: s.node?.tagName,
cls: s.node?.className,
from: s.previousRect,
to: s.currentRect,
})),
});
}
}).observe({ type: 'layout-shift', buffered: true });
buffered: true matters because it also captures shifts that happened before the observer was attached. Without it, the early shifts slip through, and those early shifts are exactly what I was looking for.
Once I had from and to, the question to ask was not what was wrong with this element, but what was above it and exactly as tall as the difference. The difference in y was 490 - 65 = 425 px. I went through the DOM above the hero looking for something 425 px tall that disappeared at around 637 ms. The only thing above the hero was the nav, and inside the nav was the mobile menu.
The actual cause: x-cloak is just an attribute without a CSS rule
The nav code looked like this, and nothing appeared wrong with it.
<nav x-data="{ open: false }">
<!-- แถบบน: โลโก้ + ปุ่มแฮมเบอร์เกอร์ -->
<button x-show="!open" @click="open = true" aria-label="เมนู">...</button>
<button x-show="open" @click="open = false" aria-label="ปิดเมนู">...</button>
<!-- เมนูมือถือ: ลิงก์ 6 ตัว + ธงภาษา 6 อัน -->
<div x-show="open" x-cloak class="md:hidden">
...
</div>
</nav>
x-show="open" with an initial value of false should keep the menu hidden, and x-cloak was already there. But both only work once Alpine has finished booting. Before that, x-show is just an attribute the browser does not recognize, while x-cloak itself hides nothing. Alpine's job is to remove that attribute once it finishes booting. Hiding the element while waiting is the job of a CSS rule I have to write myself, and this project did not have that rule in any CSS file.
The result was that while Alpine had not yet booted, a period of roughly 200-500 ms, the mobile menu appeared at its full height of 425 px, pushing the entire hero down. Once Alpine booted, x-show applied display:none to the menu, and the hero jumped back up.
A rough calculation also fits. If the viewport is 740 px tall, as the sum of y and height indicates, the affected area runs from y=65 to the bottom edge, or 675 out of 740. The distance moved is 425 out of 740. Multiplying them gives roughly 0.52, close to the reported 0.529. Something taller than half the screen disappearing all at once produces a shift above half like this.
This is hard to catch by eye because the menu appears for only a fraction of a second before disappearing. The measurements were the first indication of a problem.
One rule fixes it, but it has to be in head
<head>
<!-- ต้องมาก่อนไฟล์ CSS หลัก และต้องเป็น inline -->
<style>[x-cloak] { display: none !important; }</style>
@vite(['resources/css/app.css', 'resources/js/app.js'])
</head>
This rule hides every element with x-cloak as soon as the browser finishes reading head. When Alpine boots, it removes x-cloak, the rule stops matching, and x-show takes over control of visibility.
The position of the rule is what I need to emphasize. I put it in an inline <style> in head, not in a JS file or a CSS file loaded later.
Added through app.js or CSS loaded afterward
- The rule arrives with or after Alpine
- The element needs to be hidden before that
- The menu can still flash into view
- Depends on each user's connection speed
Inline style in head
- Arrives with the HTML, with no other file to wait for
- Takes effect before body is first painted
- One line long, with no impact on page size
- Independent of bundle loading order
As for !important, I did not add it just to look forceful. Menus or boxes with x-cloak often already have classes setting their display, such as flex or grid. If the [x-cloak] rule does not use important, those classes can win, and the element appears as though the rule did not exist.
The other half of the fix is checking which x-show elements affect layout and still have no accompanying x-cloak. Everything that takes up vertical space on the page, such as menus, notification bars, and expandable boxes, needs x-cloak. Elements floating with position absolute or fixed do not push anything, but they can still flash into view, so adding it does no harm.
Anything using <template x-if> needs to be considered separately. x-if does not hide an element; it does not create it at all until Alpine boots, so there is nothing to flash into view beforehand. But if the condition is true from the start, the element appears after booting and pushes everything below it down. That is a shift in the opposite direction to this case, which x-cloak cannot help with. The height needs to be reserved in advance instead.
Results after adding the rule
FCP also fell from 1228 ms to 508 ms, while LCP stayed at around 4884 ms, barely changing because it was a separate problem. The hero video needs a separate fix. This line of CSS does not help with that.
The fix that broke buttons across the site
The first time I wrote this rule, I did not use just [x-cloak]. I thought ahead: if there were any elements where I had forgotten x-cloak, this rule could hide those too. So I wrote this.
/* รอบแรก: ตั้งใจกันเผื่อ element ที่ลืมใส่ x-cloak — ผิด */
[x-cloak],
[x-show]:not([x-show="true"]) { display: none !important; }
This rule also brought CLS down because the menu really was hidden from the start. I thought the job was done. But when I tried using it, the hamburger button had disappeared from the nav bar, the close icon was missing, the language dropdown would not expand when clicked, and the mobile menu would not open. Everything using x-show was permanently stuck at display:none.
There are two layers to the reason. First, Alpine never rewrites the value of the x-show attribute. The attribute contains an expression, not its result. x-show="!open" stays as the string !open in the DOM for the entire lifetime of the page, whether open is true or false. The selector :not([x-show="true"]) therefore matches all of them all the time. Second, Alpine controls visibility through ordinary inline styles. To hide an element, it adds display:none; to show it, it removes that. A stylesheet rule with !important beats an inline style without important every time. No matter how many times Alpine tried to show the element, my rule overrode it with none.
The value of the x-show attribute is an expression that Alpine evaluates, not the element's current state. CSS cannot see whether that expression is currently true or false. A selector such as [x-show]:not([x-show="true"]) therefore permanently hides everything using x-show. And because the menu is still hidden from the start, CLS measurements will give no warning at all. A page that displays nothing has nothing to shift.
The fix was to remove the second selector, leaving only [x-cloak]. Guarding against forgotten x-cloak attributes needs to happen through code review, not broader CSS.
# หา x-show ที่ยังไม่มี x-cloak ในบรรทัดเดียวกัน ไล่ดูทีละตัวว่ากินพื้นที่ layout หรือเปล่า
grep -rn 'x-show=' resources/views | grep -v 'x-cloak'
# และยืนยันว่ากฎอยู่ใน head ของ layout จริง
grep -rn '\[x-cloak\]' resources/views/layouts
The lesson for me is that improved numbers are not proof of a correct fix. Low CLS can come from either fixing the problem correctly or making buttons disappear across the entire site. Measuring without actually clicking through the interface cannot distinguish the two.
A test that catches both shifts and missing buttons
After that mistake, I wrote a test that does two things in one run: click the menu to verify that it really opens and closes, then measure CLS again. It uses a viewport width of 390 px because this menu exists only on mobile.
// tools/nav-cls-check.cjs — รัน: node tools/nav-cls-check.cjs https://example.com/
const { chromium } = require('playwright');
(async () => {
const url = process.argv[2];
const b = await chromium.launch();
const p = await b.newPage({ viewport: { width: 390, height: 740 } });
await p.addInitScript(() => {
window.__cls = 0;
new PerformanceObserver(list => {
for (const e of list.getEntries()) if (!e.hadRecentInput) window.__cls += e.value;
}).observe({ type: 'layout-shift', buffered: true });
});
await p.goto(url, { waitUntil: 'load' });
await p.waitForTimeout(1500);
const bad = [];
const openBtn = p.locator('button[aria-label="เมนู"]');
const menu = p.locator('nav div.md\\:hidden');
if (!(await openBtn.isVisible())) bad.push('ปุ่มแฮมเบอร์เกอร์มองไม่เห็น');
if (await menu.isVisible()) bad.push('เมนูแสดงอยู่ทั้งที่ยังไม่ได้กด');
if (!bad.length) {
await openBtn.click();
if (!(await menu.isVisible())) bad.push('กดแล้วเมนูไม่เปิด');
await p.locator('button[aria-label="ปิดเมนู"]').click();
if (await menu.isVisible()) bad.push('กดปิดแล้วเมนูไม่หุบ');
}
const cls = await p.evaluate(() => window.__cls);
if (cls >= 0.1) bad.push('CLS ' + cls.toFixed(3) + ' เกิน 0.1');
console.log(bad.length ? '[FAIL] ' + bad.join(' / ') : '[OK] เมนูเปิดปิดได้ CLS ' + cls.toFixed(4));
await b.close();
process.exit(bad.length ? 1 : 0);
})();
Clicking the button in the test does not distort CLS because shifts that happen after user input have hadRecentInput set to true, and the observer skips them. Checking the button's isVisible() before clicking is the exact check that would have caught what I broke. If I had had this test from the start, that overly broad selector would never have reached users.
The checklist I now use before every deployment involving Alpine
- Search the whole project for
x-showandx-if, and identify which elements take up vertical space on the page. - Every
x-showthat affects layout must havex-cloakon the same tag. - Open the main layout and check that
[x-cloak] { display: none !important; }is an inline style in head before the main CSS file. - Check that no CSS selector targets the value of the
x-showattribute. - Run the buffered layout-shift observer and read y in from and to before height.
- If there is a shift, look for something above that element whose height equals the difference in y.
- Run the menu click test at 390 px to verify that it really opens and closes, then trust the CLS numbers.
This differs from the issue of images not loading on pages hidden with display:none that I wrote about before. That was something that should have appeared but did not. This was something that should have been hidden but appeared for half a second. What they share is that looking by eye alone is not enough. The browser has to report what happened.
To sum up, x-cloak hides nothing on its own. It needs one supporting CSS rule in head, and that rule must be as narrowly scoped as the documentation specifies. Do not broaden it yourself as I did. I have now moved this rule into the layout template I use to start every project so I do not have to rely on memory. If you use another library that hides elements with JS after loading, the same principle applies: anything that must be hidden from the start needs to be hidden by CSS delivered with the HTML. If I have missed anything in the explanation or made a typo, I will come back and correct it later.
Want us to set this up?
Get help with server setup, configuration, migration, or troubleshooting. Save time for the work that matters.
Hit something like this? Stuck somewhere?
Come trade notes on the LinuxThai board



Comments 0
No comments yet — be the first