This commit is contained in:
dembim 2026-02-01 10:55:42 -05:00
parent c5583de2e1
commit 95281c5720

View file

@ -16,14 +16,12 @@
// document.documentElement.className += ' invert'; // 'invert' to swap colors // document.documentElement.className += ' invert'; // 'invert' to swap colors
</script> </script>
<script defer> <script defer>
let maxH1FontSize = null;
function fitH1ToContainer(h1) { function fitH1ToContainer(h1) {
const container = h1.closest(".container"); const container = h1.closest(".container");
if (!container || window.devicePixelRatio > 2) return; if (!container || window.devicePixelRatio > 2) return;
const maxFontSize = maxH1FontSize;
const minFontSize = 8; const minFontSize = 8;
const maxFontSize = parseFloat(h1.dataset.maxFontSize);
h1.style.whiteSpace = "nowrap"; h1.style.whiteSpace = "nowrap";
h1.style.display = "inline-block"; h1.style.display = "inline-block";
@ -36,19 +34,23 @@
container.getBoundingClientRect().width - paddingLeft - paddingRight; container.getBoundingClientRect().width - paddingLeft - paddingRight;
const containerWidth = availableWidth; const containerWidth = availableWidth;
h1.style.fontSize = maxFontSize + "px";
if (h1.scrollWidth <= containerWidth) return;
let low = minFontSize; let low = minFontSize;
let high = maxFontSize; let high = maxFontSize;
let best = minFontSize; let best = minFontSize;
while (low <= high) { while (high - low > 0.1) {
const mid = Math.floor((low + high) / 2); const mid = (low + high) / 2;
h1.style.fontSize = mid + "px"; h1.style.fontSize = mid + "px";
if (h1.scrollWidth <= containerWidth) { if (h1.scrollWidth <= containerWidth) {
best = mid; best = mid;
low = mid + 1; low = mid;
} else { } else {
high = mid - 1; high = mid;
} }
} }
@ -66,18 +68,19 @@
function start() { function start() {
document.fonts.ready.then(() => { document.fonts.ready.then(() => {
const firstH1 = document.querySelector("h1"); // Store the original CSS font size on each h1
if (firstH1) { document.querySelectorAll("h1").forEach(h1 => {
maxH1FontSize = parseFloat(getComputedStyle(firstH1).fontSize); h1.dataset.maxFontSize = getComputedStyle(h1).fontSize;
} });
runFitText(); runFitText();
window.addEventListener("resize", runFitText); window.addEventListener("resize", runFitText);
}); });
} }
window.addEventListener("DOMContentLoaded", start); window.addEventListener("DOMContentLoaded", start);
</script> </script>
</head> </head>
<body> <body>