Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion src/helpers/dom.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,11 @@ export function getLineHeight(container: HTMLDivElement): number {
cloned.append(element2)
container.parentNode?.append(cloned)

const height = cloned.offsetHeight / 2
const clonedStyle = getComputedStyle(cloned)
const paddingTop = Number.parseInt(clonedStyle.paddingTop, 10)
const paddingBottom = Number.parseInt(clonedStyle.paddingBottom, 10)

const height = (cloned.offsetHeight - (paddingTop + paddingBottom)) / 2

container.parentNode?.removeChild(cloned)

Expand Down
41 changes: 41 additions & 0 deletions tests/dom.browser.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import { it, expect, describe, afterEach } from 'vitest'

import { getLineHeight } from '../src/helpers/dom.ts'

function createContainer(className: string): HTMLDivElement {
const container = document.createElement('div')

container.className = className
document.body.append(container)

return container
}

describe('getLineHeight', () => {
afterEach(() => {
document.body.replaceChildren()

for (const style of document.head.querySelectorAll('style[data-test]')) {
style.remove()
}
})

it('ignores the container vertical padding when measuring line height', () => {
const style = document.createElement('style')

style.dataset.test = 'line-height'
style.textContent = [
'.lh-base li, .lh-padded li { margin: 0; padding: 0; list-style: none; font-size: 16px; line-height: 16px }',
'.lh-padded { padding-top: 25px; padding-bottom: 25px }',
].join('\n')
document.head.append(style)

const base = createContainer('lh-base')
const padded = createContainer('lh-padded')

// The measured line height must not change just because the container
// has vertical padding. Before the fix, offsetHeight / 2 counted that
// padding, inflating the value and leaving a gap for upward menus.
expect(getLineHeight(padded)).toBe(getLineHeight(base))
})
})
Loading