Floating label input
A text box whose label moves up when you type.
A text box whose label moves up when you type.
npm install @mantine/core
First time with Mantine UI? Set it up once.
/**
* Component from Mantine UI, https://ui.mantine.dev
* MIT License, Copyright (c) 2022 Vitaly Rtischev. Full text: https://github.com/mantinedev/ui.mantine.dev/blob/master/LICENCE
*/
import { useState } from 'react';
import { TextInput } from '@mantine/core';
import classes from './FloatingLabelInput.module.css';
export function FloatingLabelInput() {
const [focused, setFocused] = useState(false);
const [value, setValue] = useState('');
const floating = value.trim().length !== 0 || focused || undefined;
return (
<TextInput
label="Floating label"
placeholder="OMG, it also has a placeholder"
required
classNames={classes}
value={value}
onChange={(event) => setValue(event.currentTarget.value)}
onFocus={() => setFocused(true)}
onBlur={() => setFocused(false)}
mt="md"
autoComplete="nope"
data-floating={floating}
labelProps={{ 'data-floating': floating }}
/>
);
}
/**
* Component from Mantine UI, https://ui.mantine.dev
* MIT License, Copyright (c) 2022 Vitaly Rtischev. Full text: https://github.com/mantinedev/ui.mantine.dev/blob/master/LICENCE
*/
.root {
position: relative;
}
.label {
position: absolute;
z-index: 2;
top: 7px;
left: var(--mantine-spacing-sm);
pointer-events: none;
color: light-dark(var(--mantine-color-gray-5), var(--mantine-color-dark-3));
transition:
transform 150ms ease,
font-size 150ms ease,
color 150ms ease;
&[data-floating] {
transform: translate(calc(var(--mantine-spacing-sm) * -1), -28px);
font-size: var(--mantine-font-size-xs);
font-weight: 500;
color: light-dark(var(--mantine-color-black), var(--mantine-color-white));
}
}
.required {
transition: opacity 150ms ease;
opacity: 0;
[data-floating] & {
opacity: 1;
}
}
.input {
&::placeholder {
transition: color 150ms ease;
color: transparent;
}
&[data-floating] {
&::placeholder {
color: var(--mantine-color-placeholder);
}
}
}