css Apply styles to form controls only if they are not empty

Utilizing an angularjs form, I have customized the following example to fit my code:

    .my-5 {
      margin:100px;
    }

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

    .form-control-placeholder {
      position: absolute;
      top: 0;
      padding: 7px 0 0 13px;
      transition: all 200ms;
      opacity: 0.5;
    }

    .form-control:focus + .form-control-placeholder,
    .form-control:valid + .form-control-placeholder {
      font-size: 75%;
      transform: translate3d(0, -100%, 0);
      opacity: 1;
    }
  <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
    <div class="container my-5">
      <div class="row">
        <div class="col-md-6 mx-auto">
          <div class="form-group">
            <input type="email" id="email" class="form-control" required>
            <label class="form-control-placeholder" for="email">email</label>
          </div>
        </div>
      </div>
    </div>

The issue arises when an invalid input is provided, causing the placeholder to revert to its initial state and position itself on the invalid input. Therefore, the objective is to maintain the floating placeholder even in the case of invalid email inputs. How can the floating placeholder be retained for invalid email inputs as well?

If I incorporate:

.form-control:invalid + .form-control-placeholder
into the current floating CSS, it will remain floating when no input is provided. The goal is to prevent it from floating when empty.

Answer №1

Right here, I utilized JavaScript to dynamically adjust CSS based on whether a specific input is empty or not. It's a relatively straightforward process.

function checkValidation(){
var inputValue = document.getElementById("email").value;

    if (inputValue.trim() == '') {
      document.getElementById('emailText').style.fontSize = ''; //reverting to default
      document.getElementById('emailText').style.opacity = '';
      document.getElementById('emailText').style.transform = '';
      //Empty therefore resetting the styles
    } else {
      document.getElementById('emailText').style.fontSize = '75%';
      document.getElementById('emailText').style.opacity = '1';
      document.getElementById('emailText').style.transform = 'translate3d(0, -100%, 0)';
      //Not empty, so adjusting the css properties.
    }
}
.my-5 {
      margin:100px;
    }

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

    .form-control-placeholder {
      position: absolute;
      top: 0;
      padding: 7px 0 0 13px;
      transition: all 200ms;
      opacity: 0.5;
    }

    .form-control:focus + .form-control-placeholder,
    .form-control:valid + .form-control-placeholder {
      font-size: 75%;
      transform: translate3d(0, -100%, 0);
      opacity: 1;
    }
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
    <div class="container my-5">
      <div class="row">
        <div class="col-md-6 mx-auto">
          <div class="form-group">
            <input onchange='checkValidation()' type="email" id="email" class="form-control" required>
            <label class="form-control-placeholder" id='emailText' for="email">email</label>
          </div>
        </div>
      </div>
    </div>

    A brief overview of the process:
    JavaScript{
      Verify user input{
        Check if it's empty{
          yes: revert to default styling
          no: apply specified transformations
        }
      }
    }

Here's a breakdown of what might have been done incorrectly:

.form-control:valid + .form-control-placeholder {

If your input field has the email type, providing text or numbers won't trigger the intended CSS changes since you're specifically looking for :valid state.

Furthermore, Detect if an input has text in it using CSS -- on a page I am visiting and do not control? addresses some confusion. "CSS has no (pseudo) selectors for value(s)". Given this limitation, leveraging JavaScript seems like the most viable solution for such scenarios.

Answer №2

Are you looking for this specific format?

.group { 
  position:relative; 
  margin: 40px;
}

.group input {
  font-size:18px;
  padding:10px 10px 10px 5px;
  display:block;
  width:300px;
  border:none;
  border-bottom:1px solid #757575;
}

.group input:focus { outline:none;}

.group input ~ label {
  color:#999; 
  font-size:14px;
  font-weight:normal;
  position:absolute;
  pointer-events:none;
  left:5px;
  top:10px;
  transition:0.2s ease all; 
  -moz-transition:0.2s ease all; 
  -webkit-transition:0.2s ease all;
}

.group input:focus ~ label, .group input:valid ~ label {
  top:-20px;
  font-size:14px;
  color: #009688;
}
<div class="group">      
  <input type="text" required>
  <label>Username</label>
</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

How to properly store response text in JavaScript variable?

Utilizing Ajax to execute a PHP script on my website, I aim to assign the response from the PHP script to a JS variable. The objective is for this script to set the variable "stopAt" to 42. This is where I encountered an issue: Below is the code snippet ...

Can you explain the differences between offsetHeight, clientHeight, and scrollHeight for me?

Have you ever wondered about the distinction between offsetHeight, clientHeight, and scrollHeight? What about offsetWidth, clientWidth, and scrollWidth? Understanding these differences is crucial for working effectively on the client side. Without this kn ...

What is the proper way to specify the type for a <video> element reference in React when utilizing Typescript?

I have been experimenting with controlling the play/pause state of a video in React.js using ref's. My code functions correctly but I am encountering tslint errors that I am currently trying to diagnose: function App() { const playVideo = (event:a ...

Is there a way to verify if all the div elements are set to display as none?

If all div elements are set to display:none, I want to display a message saying "No result found" element.each(function(i, el) { if (all elements are set to display:none) { no result found } } <div class="a" data-key="a ...

Tips for allowing divs to be dragged and resized within table cells and rows

UPDATE I believe that utilizing Jquery is the most appropriate solution for resolving my issue with the demo. Your assistance in making it work would be greatly appreciated. Thank you. My goal is to develop a scheduler application. https://i.sstatic.net ...

Arranging text within a td cell

This is what I currently have: <tr> <td colspan="4" style="font-size:7pt; font-color:red; font-weight: bold;"> PLEASE NOTE: SPECIFY THE ARTICLE IN AS MUCH DETAIL AS POSSIBLE </td> </tr> However, the text does not a ...

Clicking on two links simultaneously to avoid them being blocked as pop-ups

Is there a way to open 2 URLs at the same time with just a click? I'm open to using jquery, javascript or any other method. Priority is on efficiency and speed, but I am open to all options. I attempted using onclick in the anchor tag and also tried ...

What steps should I take to resolve the problem while in Quirks mode?

My current design includes an element with a width of 200px, along with left and right padding of 100px each. However, I have observed that in IE7, IE8, and Firefox 4, the padding is being added to the total width of the element. On the other hand, in IE ...

Some pages are receiving images from the CDN, while others are not

I am encountering some challenges while troubleshooting an issue on a website. The CDN (content delivery network) is functioning properly on some pages but not on others. Initially, I suspected a typo in the path, but that does not seem to be the case. F ...

The height of the div unexpectedly adjusts after content is displayed on hover

Within my anchor tag, there are two elements: a fontawesome Icon and a hidden span that only appears when the anchor is hovered over. The problem arises on my website when the hidden span is displayed inline causing the parent anchor to increase in height. ...

InnerHTML failing to append HTML content

Almost at the finish line with this code! I already have a footer in place, but when the button is clicked, it smoothly slides down along with its contents. Once it's done sliding, I utilize JavaScript to swap out that footer and its contents with a n ...

Retrieving localStorage data from another webpage

I recently created an account and I hope my question is clear. I have two separate pages on my website - one for a menu and the other for an HTML game. The menu has two buttons, one to start a new game and the other to continue from where you left off. How ...

Would adjusting the font sizes of headings be crossing into grey or black hat SEO territory?

Here's the scenario: In this case, the page title is designated as H3, the article title is labeled as H2, and a certain keyword or important sentence is identified as H1 within the content. These elements have custom CSS classes applied to them, cau ...

What is the best method for retrieving data using Selenium when the class name may vary slightly?

Hypothetically, let's consider the following HTML code snippet displayed on a website: <div class="box"> <div class="a1"></div> <div class="a2"></div> <div class="a3" ...

The process of manipulating the content of an HTML textarea using Selenium with Python

http://neomx.iwedding.co.kr/roundcube I attempted to change the content of a textarea, specifically the tracking number. My goal was to replace "9400111206213835724810" with "487289527385922090". However, I encountered an error message stating "ElementNot ...

Declaration of Character Encoding in CSS3

Do I need to include a character encoding declaration in CSS3? When I add the @charset "utf-8"; declaration, Visual Studio's CSS3 validation displays a warning. Can anyone offer some guidance on this issue? ...

Having trouble dynamically adding HTML elements in JQuery

I am dynamically adding HTML elements during runtime using an AJAX call from a JavaScript file. Currently, I am attempting to use a combo box drop-down element to display a list of data. Here is how I am trying to achieve this in my script: $("#myList") ...

Using flexbox to adjust the height of a block in the layout

Is there a way to modify the height of .half-containers1 and .half-containers2? Additionally, how can I create the triangle shape that is shown in the image? Is it achievable with CSS alone or do I need to use an image? Check out my fiddle for reference ...

CSS shimmer effect does not smoothly transition between borders

Currently, I'm diving into a tutorial on YouTube that teaches how to craft a CSS Glowing Border Animation After putting in the effort to replicate the animation, I noticed a glitch that's been bothering me. It seems like there's an abrupt s ...

HTML5 Local Storage allows web developers to store data locally within

After saving a value in the local storage (HTML5) on page 1, I noticed that when I navigate to page 2, the values stored in the local storage disappear. Any insights or suggestions on what might be causing this issue? Upon reviewing my code, I am using th ...