Floating Labels
See original GitHub issueDescription
Floating Labels in Chakra-UI. This topic has come up a couple of times, and given that it has a11y advantages and it is a very popular style, I think it should be part of Chakra-UI. Either as a Guide or as part of the Library.
See more: chakra-ui/chakra-ui#1744 chakra-ui/chakra-ui#5120
Problem Statement/Justification
This topic came up a couple of times, but I haven’t found a solution posted yet.
Proposed Solution or API
https://user-images.githubusercontent.com/6193042/148698023-c0226d27-b164-437c-9a13-7459e2bf6597.mov
Add floating as a variant to FormControl
form.ts
Sample:
export default {
parts: parts.keys,
baseStyle,
variants: {
floating: {
container: {
_focusWithin: {
label: {
transform: "scale(0.825) translateY(-24px) translateX(-10px)",
},
},
"input:not(:placeholder-shown) + label": {
transform: "scale(0.825) translateY(-24px) translateX(-10px)",
},
label: {
top: 0,
left: 0,
zIndex: 2,
position: "absolute",
backgroundColor: "white",
mx: 3,
px: 1,
my: 2,
},
},
},
},
}
Usage:
<FormControl variant="floating" id="first-name" isRequired isInvalid>
<Input placeholder=" " /> // <- Input needs to be before FormLabel for CSS Selector
<FormLabel>First name</FormLabel>
<FormHelperText>Keep it very short and sweet!</FormHelperText>
<FormErrorMessage>Your First name is invalid</FormErrorMessage>
</FormControl>
Alternatives
As @segunadebayo recommended in a previous ticket, this could go in as a Guide / Recipe.
Additional Information
I have built this with various approaches in client projects at this point and I figured I can put a more formal solution together to bring back into the library. Just let me know which route you want to go and I can toss something together.
Admittedly, i am a bit worried how stable it will be as part of the library, since some of the properties will be dependent on input styles. Which makes this a safer addition as a guide.
Issue Analytics
- State:
- Created 2 years ago
- Reactions:4
- Comments:5 (3 by maintainers)
@a-rezz The PR has examples for
<Select
,<Textarea
, and<Input
. Let me know if you were looking for anything else.The key for selects is to add something for
.chakra-select__wrapper + label
.Full example is here: https://codesandbox.io/s/optimistic-shockley-g0uls?file=/src/theme/components/form.ts
Thanks for your work on this and helping make a solution more visible to the community. I’ll let you know if I have any ideas or come up with something for Select. Been trying to work out a css solution as well