Display a floating label above the text input when it is focused or when it holds text

I am trying to create an animated search bar where the label moves from being over the text input to above it. I came across a helpful example in a fireship.io video, which includes the CSS and HTML code available here

The example I found demonstrates the behavior and style I want, with the label moving above and staying there when text is entered, similar to Material UI.

However, when I implement it, I only get half of the desired behavior - the label moves when I focus on the text input but then moves back regardless of entering text:

https://i.stack.imgur.com/q4pu4.jpg

https://i.stack.imgur.com/g0GXq.jpg

https://i.stack.imgur.com/xDcPB.jpg

Below is the specific HTML and CSS code I am using within a React App and SCSS file compiled using VSCode's Live SASS Watcher extension:

function searchBar() {
    return (
        <div class="SearchBar">
            <input type="text" name="Search" class="input" placeholder=""/>
            <label class="label" for="Search">Search...</label>
      </div>
    )
}



.SearchBar {
    @extend .base;
    flex-direction: column;
    position: relative;
    border-bottom: 2px dashed var(--text-primary);
    width: 50vw;
    margin: 3vh auto 3vh;
    .input {
        border: none;
        outline: none;
        overflow: hidden;
        justify-content: center;
        align-content: center;
        padding: 1rem;
        background: none;
        color: var(--text-primary);
        letter-spacing: normal;
        text-transform: none;
        font-size: 2rem;
        font-weight: bold;
        z-index: 2;
        width: 75vw;
    }
    .label {
        color: var(--text-primary);
        z-index: 1;
        position: absolute;
        transform-origin: 0%;
        transition: transform 400ms;
    }
}

.SearchBar::after {
    content: "";
    position: relative;
    display: block;
    height: 4px;
    width: 50vw;
    background: #1625ff;
    transform: scaleX(0);
    transform-origin: 0%;
    transition: transform 500ms ease;
    top: 2px;
}

.SearchBar:focus-within {
    border-color: transparent;
    .label, .input:not(:placeholder-shown) + .label {
        transform: scale(0.8) translateY(-5rem);    
    }
}

I have tried various fixes suggested in StackOverflow and other platforms without success. For instance, adding the "required" attribute did not yield the desired outcome:

<input type="text" name="Search" class="input" required/>

.SearchBar:focus-within {
    border-color: transparent;
    .label, .input:valid + .label {
        transform: scale(0.8) translateY(-5rem);    
    }
}

Similarly, moving the transformation outside the ".SearchBar:focus-within" class did not resolve the issue:

.label, .input:valid + .label {
    transform: scale(0.8) translateY(-5rem);    
}

I also attempted a solution related to autofill scenarios, as recommended here, but encountered the same problem once again.

Furthermore, experimenting with alternate syntax like using "&" instead of nesting classes produced no different outcome:

.SearchBar:focus-within {
        border-color: transparent;
        .input {
            &:focus, &:not(:placeholder-shown) &:-webkit-autofill{
                &+label {
                    transform: scale(0.8) translateY(-5rem);
                }
            }    
        }   
    }

I seem to be overlooking something crucial and unable to pinpoint the issue. At this stage, I can either achieve the label movement upon focus or have it permanently positioned above the text input, which is the final state I desire. Any insights or suggestions would be greatly appreciated.

Answer №1

To ensure there is text inside the input and maintain focus, utilize the :valid CSS selector.

HTML:

<div class="UserForm">
   <input type="text" name="Username" class="input" required/>
   <label class="label" for="Username">Username</label>
</div>

CSS:

.UserForm {
  position: relative;
  width: 300px;
  margin: 3rem auto;
}

.input {
  display: block;
  border: 1px solid #333;
  outline: none;
  padding: 0.8rem;
  font-size: 1.6rem;
  font-weight: bold;
  z-index: 2;
  width: 300px;
}

.label {
  z-index: 1;
  font-size: 1.6rem;
  color: #777;
  position: absolute;
  top: 10px;
  left: 0.8rem;
  vertical-align: middle;
  transform-origin: 0%;
  transition: all ease-in-out 300ms;
  pointer-events: none;
}

.UserForm {
  .input:valid + .label {
    color: #111;
    transform: scale(0.75) translateY(-3rem) translateX(-0.6rem);
  }
}

See a live example Here

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

Does Material-UI MenuItem pass arguments to the onClick handler function?

I am currently working with a search.js file and a search-date.js file. Within the search.js file, there is a container called SearchDate which I render. However, I'm puzzled by the behavior of the MenuItem component when it is clicked. The function ...

Implement Infinite Scrolling Pagination in WordPress

I'm completely new to Wordpress and currently utilizing the FoundationPress theme. My goal is to include a button that users can click on to load more posts. Essentially, I want users to see four blog posts initially and then be able to load the next ...

Preserve progress even after reloading the page

I am facing an issue with my React login/logout authentication implemented using Node and a database. After successfully logging in, when I refresh the page, the cookie retains the login state but the navbar menu still shows me as logged in instead of show ...

Issue during Firebase production: emptyChildrenSingleton isn't recognized

In my nextjs project, I am using React v18.1.0 and Firebase Realtime Database for handling notifications. The notifications work fine in development mode but fail in the production environment. The errors I encountered are as follows: ReferenceError: empt ...

Ensuring IconButton is perfectly aligned with Text in one straight line

I want to display IconButtons alongside plain text in a single block of text, but the result didn't turn out as I had hoped. Here is what I attempted: JS(ReactJS): <div> <span> <h3>Title</h3> <IconButton className ...

The npx command to create a new react-app doesn't seem to be functioning as expected

Encountered errors while running create react-app in the terminal. npx create react-app sample Error: EPERM: operation not permitted, mkdir 'C:\Users\Yasiru' TypeError: Cannot read property 'loaded' of undefined at exit ...

Trying to align a Material UI button to the right within a grid item

I'm attempting to right float the button below using material-ui, but I'm unsure of how to achieve this: <Grid item xs={2}> <Button variant="contained" color="secondary&quo ...

Bootstrap Tags Input - the tagsinput does not clear values when removed

I am attempting to manually remove the input value from bootstrap-tags-input when the x button is clicked, but the values are not changing in either the array or the inputs. This is the code I have tried: $('input').tagsinput({ allowDuplica ...

Tips for effectively repurposing the "public" directory within a monorepo housing several CRAs

In my monorepo, I have multiple packages that use create-react-app. Each package contains duplicated code and files in the "public" folder, such as icons, descriptions, fonts, etc. I'm looking for a solution to consolidate some or all of these common ...

Problem: The variable "$" is not defined in angular datatables causing a ReferenceError

Trying to implement Paging and sorting in my table, but encountered an error even after following all the steps mentioned here: . Tried troubleshooting the issue with no success. Ensured that all dependencies were installed properly. Below is the compo ...

Clicking on the mat-icon-button with the matSuffix in the password field will always trigger a

Seeking assistance with implementing mat-icon-button matSuffix in Angular for a login page. This is my first time working with Angular and I am facing an issue with the password field. I have used mat-icon-button matSuffix, but whenever I click on the ico ...

Align component within material-ui grid

Looking to center align the same cards but not just the grid component, I need the content itself to be equally distant from the borders and each other. I've searched and tried different solutions without luck. https://i.stack.imgur.com/aZj7H.png htt ...

Styling containers with Pandoc

Currently, I am utilizing Pandoc for the purpose of transforming Pandoc Markdown documents into HTML5 documents. Within my md input, I incorporate custom divs by employing a special Pandoc syntax, like so: ::: Resources A nice document Informative website ...

What is the updated technique for creating a full-width HTML section in 2023?

In most web designs, the content is typically "contained" to be centered and limited by a maximum width: <!DOCTYPE html> <html> <body> <div id="container" style="width: 1000px; margin: 0 auto;"> ...

Activate a button only when a value is inputted into a text box associated with a chosen radio button

I'm facing a challenge with my radio buttons and sub-options. When a user selects an option, the corresponding sub-options should be displayed. Additionally, I want to enable the next button only when text is entered in all sub-option text boxes for t ...

Showing the outcome of the AJAX call

I have searched extensively for information on how to use AJAX, but I have been unable to find a resource that clearly explains the concept and its workings. When I send an AJAX request to a PHP file using the code below, I can see the response in Mozilla ...

Issue with React Hot Toast not displaying properly due to being positioned behind the <dialog>

The Challenge of Toast Notifications Visibility with <dialog> Element tl;dr When utilizing the native dialog.showModal() function, the <dialog> element appears to consistently remain on top, which causes toast notifications to be obscured by ...

CodeIgniter: Bootstrap disables become enabled once validation is completed

My modifuser views have a disabled input field set to hold the id value. <?php echo form_open('user/updateuser'); ?> <legend>Update User</legend> <div class="form-group"> <label for="id">ID</label> ...

Stop unauthorized pages from hijacking login cookies

I have a website called where users can create their own HTML pages accessible through the link if the username is "USR" and project is "PROJECT". However, there is a security concern... Currently, I store users' login tokens as cookies. But what ...

The right side alignment is malfunctioning

I need assistance with creating a section on a webpage that resembles a piece of paper, where there is content displayed on white background against a grey background. Here's what my CSS currently looks like: body { background:grey; } .page { ...