Floating labels for input

This commit is contained in:
Lea Verou
2025-01-16 13:41:18 -05:00
parent 431e82261b
commit 2eb2597efe
2 changed files with 29 additions and 5 deletions

View File

@@ -1,4 +1,4 @@
import { html, isServer } from 'lit';
import { html, isServer, type PropertyValues } from 'lit';
import { customElement, property, query, state } from 'lit/decorators.js';
import { classMap } from 'lit/directives/class-map.js';
import { ifDefined } from 'lit/directives/if-defined.js';
@@ -57,6 +57,8 @@ import styles from './input.css';
* @cssproperty --border-color - The color of the input's borders.
* @cssproperty --border-width - The width of the input's borders. Expects a single value.
* @cssproperty --box-shadow - The shadow effects around the edges of the input.
*
* @cssstate blank - The input is empty.
*/
@customElement('wa-input')
export default class WaInput extends WebAwesomeFormAssociatedElement {
@@ -308,6 +310,14 @@ export default class WaInput extends WebAwesomeFormAssociatedElement {
this.passwordVisible = !this.passwordVisible;
}
updated(changedProperties: PropertyValues<this>) {
super.updated(changedProperties);
if (changedProperties.has('value')) {
this.toggleCustomState('blank', !this.value);
}
}
@watch('step', { waitUntilFirstUpdate: true })
handleStepChange() {
// If step changes, the value may become invalid so we need to recheck after the update. We set the new step

View File

@@ -81,22 +81,36 @@
}
}
/* Floating label */
/**
* Floating labels
*/
&::part(label) {
transition: all var(--wa-transition-normal);
position: absolute;
top: calc(var(--wa-form-control-height) / 2 - 0.5lh);
left: calc(var(--wa-space) - 0.25em);
z-index: 1;
/* State: out of the way by default */
top: -0.5lh;
font-size: var(--wa-size-smaller);
background-color: var(--wa-form-control-background-color);
padding-inline: 0.25em;
}
&:focus::part(label) {
top: -0.5lh;
color: var(--wa-color-focus);
font-size: var(--wa-size-smaller);
}
/* State: placeholder-like when:
* - the input is empty
* - the input is not focused
* - there is no actual placeholder
*/
&:state(blank):not(:focus, [placeholder])::part(label) {
top: calc(var(--wa-form-control-height) / 2 - 0.5lh);
font-size: inherit;
}
/* Different positioning and appearance for filled */