Search code examples
csssass

How do i make the last char red in input placeholder?


This is my input field enter image description here, i want to change the last char '*' to be red instead of transparent black.

I have tried a lot of different approaches but none of them works, any help would be appreciated.


Solution

  • You can give the placeholder another color using the ::placeholder selector. However, to give only one letter another color is not possible.

    You can achieve what you want by creating a custom input element, using HTML and CSS.

    /**
     * Just a basic idea of how you can achieve what you want using HTML and CSS only.
     */
    
    .input {
      background-color: #fff;
      border-radius: 3px;
      position: relative;
      display: inline-block;
      border: 1px solid #888;
    }
    
    input {
      background-color: transparent;
      position: relative;
      padding: 5px;
      z-index: 1;
      border: none;
    }
    
    .placeholder {
      position: absolute;
      color: #ccc;
      left: 5px;
      top: 50%;
      transform: translateY(-50%)
    }
    
    /* Add the asterix when the input is required */
    input:required + .placeholder::after {
      content: "*";
      color: red;
    }
    
    /* Hide the placeholder when the user wants to fill the input */
    input:focus + .placeholder {
      visibility: hidden;
      opacity: 0;
    }
    <div class="input">
      <input type="text" name="name" required />
      <span class="placeholder">Your name</span>
    </div>

    Remove the placeholder="" from your input and place the text inside the custom span element with the classname placeholder.

    When the input is required the CSS will append a asterix.