skip to Main Content
div:empty:not(:focus):before {
          content: attr(data-text);
      }
      div:focus:before {
          content: "";
      }
<div data-text="placeholder text..."></div>

The placeholder text is shown by CSS but when I click the div element, placeholder text doesn’t get hidden.

What is wrong with this approarch, div:focus:before?

2

Answers


  1. The :focus pseudo-class only applies to elements that can receive focus, such as form elements (<input>, <select>, etc.) and links (<a>). The <div> element in your code cannot receive focus by default, so the :focus pseudo-class doesn’t work.

    <!DOCTYPE html>
    <html lang="en">
    
    <head>
      <style>
        div:empty:not(:focus):before {
          content: attr(data-text);
        }
    
        div:focus:before {
          content: "";
        }
      </style>
    </head>
    
    <body>
      <div tabindex="0" data-text="placeholder text..."></div>
    </body>
    
    </html>

    This code will allow the <div> element to receive focus when the user clicks on it or tabs to it using the keyboard. With the tabindex attribute set, the :focus pseudo-class will work as expected, and the placeholder text will be hidden when the <div> element is in focus.

    Login or Signup to reply.
  2. Try to change your <div> element for <input> or <textarea> like

    <input type="text" placeholder="placeholder text...">
    
    <textarea placeholder="placeholder text..."></textarea>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search