Skip to content

Commit 1c8a3cc

Browse files
authored
feat: account for scroll margin (#1197)
1 parent 3e2be26 commit 1c8a3cc

File tree

1 file changed

+15
-1
lines changed

1 file changed

+15
-1
lines changed

src/index.ts

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,16 @@ const getOptions = (options: any): StandardBehaviorOptions => {
7171
return { block: 'start', inline: 'nearest' }
7272
}
7373

74+
const getScrollMargins = (target: Element) => {
75+
const computedStyle = window.getComputedStyle(target)
76+
return {
77+
top: parseFloat(computedStyle.scrollMarginTop) || 0,
78+
right: parseFloat(computedStyle.scrollMarginRight) || 0,
79+
bottom: parseFloat(computedStyle.scrollMarginBottom) || 0,
80+
left: parseFloat(computedStyle.scrollMarginLeft) || 0,
81+
}
82+
}
83+
7484
// Determine if the element is part of the document (including shadow dom)
7585
// Derived from code of Andy Desmarais
7686
// https://terodox.tech/how-to-tell-if-an-element-is-in-the-dom-including-the-shadow-dom/
@@ -127,14 +137,18 @@ function scrollIntoView<T = unknown>(
127137
return
128138
}
129139

140+
const margins = getScrollMargins(target)
141+
130142
if (isCustomScrollBehavior<T>(options)) {
131143
return options.behavior(compute(target, options))
132144
}
133145

134146
const behavior = typeof options === 'boolean' ? undefined : options?.behavior
135147

136148
for (const { el, top, left } of compute(target, getOptions(options))) {
137-
el.scroll({ top, left, behavior })
149+
const adjustedTop = top - margins.top + margins.bottom
150+
const adjustedLeft = left - margins.left + margins.right
151+
el.scroll({ top: adjustedTop, left: adjustedLeft, behavior })
138152
}
139153
}
140154

0 commit comments

Comments
 (0)