Publik alignment
by phloe
HTML
<link href="https://www.dr.dk/global/publik.css" rel="stylesheet" />
<input id="fontSize" type="range" max="120" min="6" value="48" />
<input id="lineHeight" type="range" max="2.5" min="0.5" value="1.2" step="0.05" />
<div class="resp-box"></div>
<div class="box">
<span class="text" id="text">Hello world<br/>How are you?</span>
</div>
<div class="box">
<span class="text" id="textRounded">Hello world<br/>How are you?</span>
</div>
CSS
html {
font-family: Publik;
--ascender: var(--dr-font-publik-ascender, 1);
--cap-height: var(--dr-font-publik-cap-height, 0.69);
--descender: var(--dr-font-publik-descender, 0.2);
--line-height-normal: calc(var(--ascender) + var(--descender));
--vertical-offset: calc((var(--descender) - (var(--ascender) - var(--cap-height))) / 2);
--leading-normal: calc((var(--line-height-normal, 1) - 1) / 2);
--leading-top: calc((var(--ascender) - var(--cap-height)) - var(--leading-normal, 0));
--leading-bottom: calc(var(--descender) - var(--leading-normal, 0));
}
.box {
background-color: red;
border: 20px solid black;
line-height: 0;
margin: 20px 0;
}
.text {
--font-size: 48px;
--line-height: 1.2;
--leading: calc((var(--line-height, 1) - 1) / 2);
color: white;
line-height: var(--line-height);
font-size: var(--font-size);
vertical-align: top;
display: inline-block;
}
.text::before {
content: "";
display: table;
margin-bottom: calc((var(--leading-top) + var(--leading, 0)) * -1em);
}
.text::after {
content: "";
display: table;
margin-top: calc((var(--leading-bottom) + var(--leading, 0)) * -1em);
}
.resp-box {
background-color: cyan;
}
.resp-box::after {
content: "";
display: table;
padding-bottom: 16.25%;
}
JavaScript
const ascender = 1;
const descender = 0.2;
const capHeight = 0.69;
const lineHeightNormal = ascender + descender;
const centerOffset = ((ascender - capHeight) - descender) / 2;
// text.style.verticalAlign = `${centerOffset}em`;
fontSize.addEventListener("input", function() {
text.style.setProperty("--font-size", `${fontSize.value}px`);
textRounded.style.setProperty("--font-size", `${fontSize.value}px`);
calcLeading();
});
lineHeight.addEventListener("input", function() {
text.style.setProperty("--line-height", `${lineHeight.value}`);
textRounded.style.setProperty("--line-height", `${lineHeight.value}`);
calcLeading();
});
function calcLeading() {
const height = fontSize.value * capHeight;
const flooredHeight = Math.floor(height);
const baseLine = ((lineHeight.value - lineHeightNormal) / 2) + ascender;
const baseLineRounded = Math.round(baseLine * fontSize.value) / fontSize.value;
console.log("calcLeading", baseLine, baseLineRounded);
textRounded.style.setProperty("--leading-top", baseLineRounded - capHeight);
textRounded.style.setProperty("--leading-bottom", (lineHeight.value - (baseLineRounded)));
}