What is the best way to incorporate a floating label into an input field?

My goal is to create a form where the label of the input field moves up when the user starts typing, and stays up if they enter any text. However, if the user leaves the input area blank, the label should revert back to its original position.

I have tried implementing this functionality with an input box that has the "required" attribute, and it works as expected. But when I apply the same concept to an input field without the required attribute and enter some content, the label moves back down instead of staying up.

div{
  margin-top:40px;
}
.btn-add input[type="text"]{
    width: 90%;
    padding: 10px 20px 0 20px;
    border: none;
    border-bottom:1px solid #999;
    font-size: 140%;
    color: #000;
}
.btn-add input:focus ~ .floating-label{
    top: -20px;
    bottom: 10px;
    left: 10px;
    font-size: 20px;
    opacity: 1;
    color: rgb(100, 6, 6);   
}
.floating-label {
    position: absolute;
    pointer-events: none;
    left: 20px;
    top:10px;
    transition: 0.2s ease all;
    color: #999999;
    font-size: 120%;
}
.form-float{
    position: relative;
}
<div class="form-float btn-add"> 
     <input type="text" class="inputText" placeholder="" >                             
     <label class="floating-label" >Button text</label>                        
</div>

To overcome this issue, I removed

input:not(:focus):valid~.floating-label
so that it can work properly even with non-required fields.

Answer №1

Use the following code to address issues with placeholders.

.form-group {
  position: relative;
  margin-bottom: 1.5rem;
}

input + .form-control-placeholder {
  position: absolute;
  transition: all 200ms;
  top: -20px;
    bottom: 10px;
    font-size: 20px;
    opacity: 1;
    color: rgb(100, 6, 6);
}

input:placeholder-shown + .form-control-placeholder {
      position: absolute;
    pointer-events: none;
    left: 20px;
    top:10px;
    transition: 0.2s ease all;
    color: #999999;
    font-size: 120%;
}

.form-control:focus + .form-control-placeholder {
  position: absolute;
  transition: all 200ms;
    top: -20px;
    bottom: 10px;
    font-size: 20px;
    opacity: 1;
    color: rgb(100, 6, 6);
}
input[type="text"]{
    width: 90%;
    padding: 10px 20px 0 20px;
    border: none;
    border-bottom:1px solid #999;
    font-size: 140%;
    color: #000;
}
label{
    position: absolute;
    pointer-events: none;
    left: 20px;
    top:10px;
    transition: 0.2s ease all;
    color: #999999;
    font-size: 120%;
}
<br>
<br>
<div class="form-group">
  <input type="text" class="form-control" placeholder=" " >
  <label class="form-control-placeholder">Button text</label>
</div>

Answer №2

To add space to your placeholder by default, you can use the input:not(:placeholder-shown) property to check if the input is empty or not. Here is a working example of the code:

div{
  margin-top:40px;
}
.btn-add input[type="text"]{
    width: 90%;
    padding: 10px 20px 0 20px;
    border: none;
    border-bottom:1px solid #999;
    font-size: 140%;
    color: #000;
}
.btn-add input:focus ~ .floating-label{
    top: -20px;
    bottom: 10px;
    left: 10px;
    font-size: 20px;
    opacity: 1;
    color: rgb(100, 6, 6);   
}
.btn-add input:not(:placeholder-shown) ~ .floating-label{
  top: -20px;
    bottom: 10px;
    left: 10px;
    font-size: 20px;
    opacity: 1;
    color: rgb(100, 6, 6); 
}

.floating-label {
    position: absolute;
    pointer-events: none;
    left: 20px;
    top:10px;
    transition: 0.2s ease all;
    color: #999999;
    font-size: 120%;
}
.form-float{
    position: relative;
}
<div class="form-float btn-add"> 
     <input type="text" class="inputText" placeholder=" " >                             
     <label class="floating-label" >Button text</label>                        
</div>

Answer №3

If you want to show placeholder text only when it is filled in, you can achieve this using the visibility property.

div {
    margin-top:40px;
}
.btn-add input[type="text"] {
    width: 90%;
    padding: 10px 20px 0 20px;
    border: none;
    border-bottom:1px solid #999;
    font-size: 140%;
    color: #000;
}
.floating-label {
    position: absolute;
    pointer-events: none;
    left: 20px;
    top: -20px;
    transition: 0.2s ease all;
    color: #999999;
    font-size: 120%;
}
.form-float input:placeholder-shown ~ label {
    top: 0;
    visibility: hidden;
}

.form-float {
    position: relative;
}
<div class="form-float btn-add"> 
    <input type="text" placeholder="Button Label" >                             
    <label class="floating-label">Button Label</label>
</div>

Answer №4

I have come up with two potential solutions that may require some tweaking as they might not be entirely accurate:

Solution #1: Implementing a floating label on focus

    .custom-form-input {
            display: block;
            width: 100%;
            height:32px;
            padding: 1rem .55rem .065rem .55rem;
            font-weight: 400;
            border: 1px solid #cad3d6;
            transition: border-color .15s ease-in-out, box-shadow .15s ease-in-out;
            background-color: #fafafa;
            font-size: 0.79em;
            color:#000000;
            border-radius: 2px;
            font-family: Arial, Helvetica, sans-serif;
        }
        
        .custom-form-input:focus,
        .custom-form-input:active {
            color: #212529;
            background-color: #fff;
            border-color: #585d61;
            outline: 0;
        }
        
        .custom-form-floating {
            position:relative;
        }
        
        .custom-form-floating-label {
            position:absolute;
            color: #9aa0a9;
            font-size: 0.85em;
            height:100%;
            width:100%;
            top: 0px;
            display:flex;
            align-items: center;
            padding: 0 .55rem 0 .55rem;
            transition: 0.2s ease all;
            -moz-transition: 0.2s ease all;
            -webkit-transition: 0.2s ease all;
            user-select: none;
            pointer-events: none 
        
        }
        
        .custom-form-input:focus ~ label,
        .custom-form-input:valid ~ label {
          font-size: 0.65rem;
          height:55%;
        }

.wrapper {
  width:150px;
}
<div class="custom-form-floating">
         <input id="test" class="custom-form-input" aria-label="username or email" required=true aria-required="true"/>
         <label for="test" class="custom-form-floating-label">Example 1</label>
</div>


<div class="wrapper">
  <div class="custom-form-floating">
         <input id="test" class="custom-form-input" aria-label="username or email" required=true aria-required="true"/>
         <label for="test" class="custom-form-floating-label">Example 2</label>
  </div>
</div>

Solution #2: Applying a floating label when typing a letter

.custom-form-input {
    display: block;
    width: 100%;
    height: 5px;
    font-weight: 400;
    border: 1px solid #cad3d6;
    transition: border-color .15s ease-in-out;
    background-color: #fafafa;
    font-size: 1.2em;
    color: #000000;
    padding: 1rem .50rem 1rem .50rem;
    border-radius: 2px;
    font-family: Arial, Helvetica, sans-serif;
}

.custom-form-input:focus,
.custom-form-input:active {
    color: #212529;
    background-color: #fff;
    border-color: #585d61;
    outline: 0;
}

.custom-form-floating {
    position: relative;
}

.custom-form-floating-label {
    position: absolute;
    color: #9aa0a9;
    font-size: 0.85em;
    height: 100%;
    width: 100%;
    top: 0px;
    display: flex;
    align-items: center;
    padding: 0 .55rem 0 .55rem;
    transition: 0.2s ease all;
    -moz-transition: 0.2s ease all;
    -webkit-transition: 0.2s ease all;
    user-select: none;
    pointer-events: none
}

.custom-form-input:valid {
    padding: 1.50rem .50rem .50rem .50rem;
    font-size: 0.79em;
}

.custom-form-input:valid~label {
    font-size: 0.65rem;
    height: 55%;
}

.wrapper {
  width:250px;
}
        
        
<div class="wrapper">
  <div class="custom-form-floating">
                            <input id="test" class="custom-form-input"
                                aria-label="username or email" required=true aria-required="true"/>
                            <label for="test" class="custom-form-floating-label">Email or username</label>
                        </div>
</div>
        
        
      

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The problem of SVG rendering order requires a solution that does not rely on javascript

I am new to experimenting with inline svg, and I wanted to share my code: <svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="350" height="350"> <defs> <style> .ring { transform-origin: 175px 175px; } ...

When selecting an option in the burger menu, the dropdown does not react properly

I am facing an issue with the burger menu where one of the options should trigger a dropdown, but the content is not adjusting properly. The dropdown menu should push the other content downward, but currently, it overlaps. I have included the code for th ...

Stop the Nav bar item from collapsing

Alright, let's talk about the scenario: The situation is that I have a basic, plain, nav nav-tabs navigation bar with a few elements and a rightmost item (with pull-right) positioned as an <li> element which includes a dropdown. As the window ...

How to vertically align content using Zurb Foundation's equalizer feature?

I am currently utilizing Zurb Foundation 5 along with the equalizer component. In a scenario where I have three columns of equal width, I am aiming to achieve vertical center alignment for the content (text) in the middle column and vertical bottom alignme ...

What is the best way to combine PHP with HTML in your code?

I am looking to display data from a database in a table format. Additionally, I want to include images sourced from the same database. Using AJAX, I have a function called getPosts that fetches data from getPosts.php and populates a table with it. Althou ...

What is the method for updating the value of the Sass variable in Angular 4?

Within the file app.component.scss, there is a variable named $color that has been set to 'red'. What steps can be taken within the file app.component.ts in order to access this variable and change its value to 'green'? ...

What method can I use to replace the status bar from the top?

Is there a way to smoothly slide in and out a <View/> on React Native iOS, similar to the animation sequences shown in the images below? ...

Finding the webpage URL where a form element is located

Suppose I have two pages called a.php and b.php, each with a form-tag. Both of these forms have the same action attribute set to c.php. Is there a way to determine in c.php which form (from either page a or b) triggered its submission? Using a hidden inpu ...

Creating a navigation bar that smoothly slides into view from the top

In my Angular app (version 2+), the current code I have is: .header { background: rgba(white, 0); &.fixed-top { background: rgba(white, 1); border-bottom: solid whitesmoke 1px; position: fixed; top: 0; right: 0; left: 0; ...

Is it possible for an ul to be displayed beneath a white section within an li

I am working on a JQuery carousel that is displaying correctly, but I want to make a small adjustment to the content: <li class="jcarousel-item jcarousel-item-horizontal jcarousel-item-1 jcarousel-item-1-horizontal" style="float: left; list-style: none ...

Is there a way to prevent my Header links from wrapping during window size testing?

https://i.stack.imgur.com/YTc3F.png The image above showcases my standard header layout, while the one below illustrates what occurs as I resize the window. https://i.stack.imgur.com/re44T.png Is there a specific CSS solution to prevent the Text navLink ...

iOS Safari enlarges frameset beyond viewport limits

I am currently designing a website that utilizes a frameset featuring a horizontal split - a menu sidebar on the left and a content area. <!DOCTYPE html> <html> <head> <title>Frameset Test</title> </head> ...

Fading in and out occurs several times while scrolling through the window

My goal is to update the logo image source with a fadeIn and fadeOut effect when scrolling up or down. The issue I'm facing is that the effect happens multiple times even after just one scroll, resulting in the logo flashing many times before finally ...

What is the best way to display table rows for a specified date range?

I am working with a table and need to display only the rows that fall between two specific dates. <table id ="Table"> <thead> <tr> <th>Date</th> <th>Name</th> <th>Desc</th> </tr> </thead> ...

The scroll feature in JavaScript is malfunctioning

After countless hours of troubleshooting, I still can't figure out why the code snippet below is not working properly on my website at : <script> $(window).scroll(function () { if ($(window).scrollTop() > 400) { ...

What is a solution to prevent style.css from being recognized as the Jekyll Page?

Currently, I am utilizing an expression {% assign mypages = site.pages | sort: "order" %} {% for page in mypages %} {% unless page.exclude %} <a href="{{page.url|absolute_url}}"> {{ page.shortname }} <span class="rate">{% include indexmod.h ...

Facing difficulties with the XPATH due to an inability to access specific parts of the HTML code

Currently, I am facing an issue where I need to click on a link using Selenium and Java. When searching for the link using XPath, I am encountering a problem where only white spaces are displayed instead of most of the webpage content. The highlighted link ...

What methods can you use to locate the CSS selector within HTML that meets certain criteria?

Is it possible to parse a given link and find CSS selectors with attributes that partially or completely match a specific keyword? For example, if the keyword is "print," I want to identify all CSS selectors in the link containing "print" in their name, id ...

The directive code takes precedence over the controller code and is executed first

A custom directive has been implemented and is utilized as shown below: <div car-form car="car" on-submit="createCar(car)"></div> This directive is used on both the new and edit pages, each with its own controller. The EditCarController retri ...

Avoiding the separation of hyphenated words when they overflow on a new line

My code is designed to limit text to two lines and show an ellipsis if there is more content. However, I am facing an issue with hyphenated words like "breath-taking" not being treated as one word. Instead, they are often cut off at the end of the second l ...