useKeyboardFit watches visualViewport and reports how much of the screen the on-screen keyboard covers. The same numbers go to CSS variables on <html>, so bottom bars and chat inputs can sit above the iOS keyboard, which overlays the page instead of resizing it.
Browser Support
Tracks the viewport when the keyboard opens.
Preview
- Keyboard
- closed
- --keyboard-height
- 0px
- --viewport-height
- --viewport-top
On a desktop the keyboard stays closed. Open this page on a phone, tap the field and watch the values.
Installation
Usage
import { Input } from "@/components/ui/input"
import { useKeyboardFit } from "@/hooks/use-keyboard-fit"
export function ChatComposer() {
// call it once, high in the tree; it also sets the CSS variables
const { open } = useKeyboardFit()
return (
<form
className="fixed inset-x-0 bottom-[var(--keyboard-height,0px)] border-t bg-background p-2"
data-raised={open}
>
<Input className="w-full" placeholder="Message" />
</form>
)
}Examples
Pinned bar above the keyboard
Drag the slider to see what --keyboard-height does to a fixed bar. On a real phone the hook sets the value for you.
.composer {
position: fixed;
inset-inline: 0;
bottom: var(--keyboard-height, 0px);
}Fit a screen into the visible area
--viewport-height and --viewport-top describe the part of the page you can see. Size a full-screen form with them to keep the task and the field in view.
html[data-keyboard-open] .quiz-screen {
position: fixed;
top: var(--viewport-top);
height: var(--viewport-height);
}Any focused element
By default the keyboard counts as open only while a text field has focus, which filters out zoom and toolbars. Turn it off for custom editors.
const { height } = useKeyboardFit({ requireFocus: false, minHeight: 80 })Parameters
| Name | Type | Default | Description |
|---|---|---|---|
| options.minHeight | number | 120 | Smaller overlaps count as browser toolbars, not a keyboard |
| options.requireFocus | boolean | true | Count the keyboard as open only while a text field is focused |
| options.disabled | boolean | false | Stop tracking and remove the CSS variables |
Returns
| Name | Type | Description |
|---|---|---|
| height | number | Height of the screen covered by the keyboard, in px. 0 when closed |
| open | boolean | Whether the keyboard is open |
| --keyboard-height | CSS | Same as height, on <html> |
| --viewport-height / --viewport-top | CSS | Size and offset of the visible area |
| data-keyboard-open | attribute | Present on <html> while the keyboard is open |
Features
- Ignores pinch zoom. Zooming in also shrinks the visible area, but scale above 1 is not treated as a keyboard
- Works in installed web apps. Compares against the tallest height seen at the current width, which also covers apps launched from the home screen
- Cleans up. On unmount the variables and the attribute are removed from <html>