Using shifting label field (in CSS) without the need for a required attribute

My challenge involves creating a floating label for a styled input using only CSS. The issue arises when I realize that this implementation requires the input to have the required attribute in order for the label to function properly (using pure CSS). Is there a way to achieve this without having to use the required attribute, as its presence is causing complications with form validations? Below is a snippet of my HTML markup and CSS styling:

.myInput {
  position: relative;
  input {
    padding: 30px 10px 10px;
    display: block;
    width: 100%;
    border: 1px solid black;
    &:focus {
      outline: none;
    }
    &:focus~label,
    &:valid~label,
    &:placeholder-shown~label {
      top: 10px;
      color: black;
    }
  }
  label {
    color: red;
    position: absolute;
    pointer-events: none;
    left: 10px;
    top: 20px;
    transition: 0.2s ease all;
    -moz-transition: 0.2s ease all;
    -webkit-transition: 0.2s ease all;
  }
}



<div class="myInput">
  <input type="text" required id="target" />
  <label htmlFor="target">
        label
    </label>
</div>

Upon removing the required attribute from the input field, the label no longer transitions into the placeholder spot when the input is empty. Here's a link to a demonstration on JSFiddle - https://jsfiddle.net/1ob2npcu/2/

I am exploring possibilities to accomplish this purely through CSS – I am utilizing SCSS for this task. Any insights or solutions would be greatly appreciated. Thank you!

Answer №1

In the event that you decide to eliminate the required attribute, it is also necessary to omit

&:valid~label

from the CSS. In this case, you will be required to specify a placeholder for the input and reverse the logic for the placeholder-shown pseudoclass. Consequently, the SCSS style for the input should be adjusted as follows:

input {
    padding: 30px 10px 10px;
    display: block;
    width: 100%;
    border: 1px solid black;

    &::placeholder { 
       color: transparent;
    }

    &:focus {
        outline: none;
    }

    &:focus ~ label,
    &:not(:placeholder-shown) ~ label{
        top: 10px;
        color: black;
    }

}

It is worth noting that the appropriate attribute in the label tag should be for, not htmlfor.

Check out my jsfiddle fork

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

Deleting sections of a string using JavaScript

I've encountered a rather unique issue where I need to address a bug on a website. The problem is that when a string is generated dynamically, it automatically adds 5 spaces before and after the string. Ideally, this should be fixed in the backend cod ...

Attempting to change the src of a different image using jQuery upon clicking

I have two separate divs that change their background image source when clicked, which is working fine. However, I would like them to change the other image they are paired with. For example, if div 1 is clicked and becomes "open", then if div 2 is "open" ...

Enter a number into a text box and increase the value in several text boxes created with jQuery in PHP

I need to dynamically populate textboxes with student information from a database after inputting a value, for example 100, and clicking on the 'Add' button. The challenge is to incrementally assign values to each textbox based on the initial num ...

Emulating form functionality: How to programmatically open a link using PHP

Do you want to provide package tracking on your website like DHL does? With DHL, users can track their packages by visiting a specific URL, such as . When a tracking number is entered, it opens a new window with the following format: SOMENUMBER1234 If you ...

"Returning undefined: The outcome of using jQuery's .html() method on

I am having an issue with the JavaScript function I have created to load content from another URL into the current document. For some reason, both contentHtml and menuHtml variables are showing as undefined. Can someone please help me identify where I we ...

Tips for highlighting the final word in the headline using an underline

I'm attempting to create a title style similar to what is shown below https://i.sstatic.net/Qao4g.png The issue I'm facing is achieving the underline effect. I tried using title:after but it didn't give me the exact result I'm looking ...

Use JavaScript to convert only the initial letter to uppercase

Once again, I am in the process of learning! Apologies for the simple questions, but learning is key... Attempting to implement a trick I found online to change all letters to uppercase, I am now trying to adjust it to only capitalize the first letters. T ...

Using JavaScript to ensure that a background image is only displayed once in an HTML document

I am currently working with two cells, where I have set background images for these cells using Javascript from an array of images. The images available are: image1= 150*150 referred to as image1 once image2=150*150 referred to as image2 once However, ...

Dropdown selection returning the text value instead of the designated value

Is it possible to retrieve the text "Region 1" instead of just the value '1' from a dropdown menu in PHP? <select name = 'region' id = 'region'> <option value = '1'>Region 1</option> <select&g ...

Concealing collapsible Bootstrap 4 navbar with a single click

<nav class="navbar navbar-expand-lg navbar-dark bg-dark fixed-top" id="myNavbar"> <div class="container"> <a class="navbar-brand" href="#Home"></a> <button class="navbar-toggler" type="button" data-toggle="collap ...

Ensuring the HTML5 video poster matches the dimensions of the video content

Is there a way to adjust the HTML5 video poster so it perfectly fits the dimensions of the video itself? Check out this JSFiddle demonstrating the issue: http://jsfiddle.net/zPacg/7/ Here's the code snippet: HTML: <video controls width="100%" h ...

Adding a new .row in Angular based on an ngFor condition

As a newcomer to Angular, I decided to take on their tutorial with a few modifications. I have created an array as follows: export const HEROES: Hero[] = [ { id: 11, name: 'Mr. Nice' }, { id: 12, name: 'Narco' }, { id: 13, name: ...

Please fill out and submit a form by clicking on a button in HTML

I am currently developing a software program that needs to automatically submit a form on a webpage by "clicking" on a button: <button class="form" type="submit">Send</button> Based on my limited knowledge, I understand that in order to submi ...

What is the best way to maintain an input String when refreshing a page using Selenium Webdriver?

When using Selenium webdriver, I am facing an issue where the value in an input element is not retained after refreshing the page. Interestingly, when testing manually, the scenario works as expected. Is there a way to ensure that the input string remain ...

Using the "export default" feature in React.js is a

Is it possible to name an exported function as "default" without encountering an error? export default() => { const [width, setWidth] = useState(0); const [height, setHeight] = useState(0); useEffect(() => { setTimeout(() => { setWidth(window.i ...

center a horizontal line using StyledSheets in your project

After drawing a horizontal line, I noticed that it is positioned towards the left side of the screen. I am hesitant to increase its width. Are there any other methods to move it to the center? I attempted wrapping it with another view and using alignConten ...

Switching website to mobile version when accessed on a handheld device

Although I'm sure this question has been asked before, I can't seem to find any information on it. I am interested in creating two versions of my website - one specifically for mobile displayed on a subdomain like m., and another version for desk ...

Eliminate the lower boundary of a divisional table

I'm having an issue with displaying images in a div table. Each image has a border at the bottom, which is around 2-5 pixels wide. Unfortunately, as a new user, I am unable to send any images. My main goal is to remove this unwanted border from the ...

Navigating to different HTML pages by utilizing <a> elements in Angular 2

As a newcomer to Angular 2, I've decided to build my personal website using this framework. The main page of my website contains bio information, while the other page will feature blog content. Both pages will have a shared header and footer, but diff ...

How can we use jQuery to extract an HTML element's external stylesheet and add it to its "style" attribute?

My goal is to extract all CSS references from an external stylesheet, such as <link rel="stylesheet" href="css/General.css">, and add them to the existing styling of each HTML element on my page (converting all CSS to inline). The reason for this re ...