1
0
mirror of https://github.com/phuoc-ng/csslayout.git synced 2025-08-06 14:16:50 +02:00
Files
csslayout/contents/floating-label.mdx
2023-10-06 18:20:10 +07:00

122 lines
2.3 KiB
Plaintext

---
category: Input
created: '2019-11-28'
description: Create a floating label with CSS
keywords: css floating label, placeholder shown
thumbnail: /assets/css-layout/thumbnails/floating-label.png
title: Floating label
---
## HTML
```html index.html
<div class="floating-label">
<!-- The input -->
<input placeholder="Placeholder" class="floating-label__input" />
<!-- The label -->
<label class="floating-label__label">Placeholder</label>
</div>
```
## CSS
```css styles.css
.floating-label {
border: 1px solid #d1d5db;
border-radius: 0.25rem;
position: relative;
}
.floating-label__input {
border: none;
padding: 0.5rem;
height: 100%;
}
/*
Show the label at desired position when the
placeholder of input isn't shown
*/
.floating-label__input:not(:placeholder-shown) + .floating-label__label {
background: #fff;
transform: translate(0, -200%);
opacity: 1;
}
.floating-label__label {
/* Position the label */
left: 1rem;
position: absolute;
top: 100%;
/* Hide it by default */
opacity: 0;
transition: all 200ms;
padding: 0 0.5rem;
}
```
Type something in the input to see how the label is shown up.
<Playground>
```css styles.css hidden
body {
align-items: center;
display: flex;
justify-content: center;
}
.floating-label {
border: 1px solid #d1d5db;
border-radius: 0.25rem;
position: relative;
/* Demo */
padding: 0px 1px;
height: 2.5rem;
}
.floating-label__input {
border: none;
padding: 0.5rem;
height: 100%;
}
/*
Show the label at desired position when the
placeholder of input isn't shown
*/
.floating-label__input:not(:placeholder-shown) + .floating-label__label {
background: #fff;
transform: translate(0, -200%);
opacity: 1;
}
.floating-label__label {
/* Position the label */
left: 1rem;
position: absolute;
top: 100%;
/* Hide it by default */
opacity: 0;
transition: all 200ms;
padding: 0 0.5rem;
}
```
```html index.html hidden
<div class="floating-label">
<input placeholder="Placeholder" class="floating-label__input" />
<label class="floating-label__label">Placeholder</label>
</div>
```
</Playground>
## See also
- Explore some ways to [animate a floating label](https://phuoc.ng/collection/css-animation/floating-label/).