0

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?

LS_
  • 6,763
  • 9
  • 52
  • 88
UK4
  • 460
  • 7
  • 25
  • as suggested [here](https://stackoverflow.com/a/3656524/3789527) you can add `tabindex="0"` to your `div` – LS_ Mar 23 '23 at 16:32

2 Answers2

0

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.

-1

Try to change your <div> element for <input> or <textarea> like

<input type="text" placeholder="placeholder text...">

<textarea placeholder="placeholder text..."></textarea>