Show placeholder text with a p tag with CSS only, when it's empty or there is a br tag inside

I’m trying to show a placeholder text to a p tag.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Test</title>
  <style>
      p:empty:not(:focus):before,
      p br:only-child:not(:focus):before {
          content: attr(data-text);
      }
  </style>
</head>
<body>
<p data-text="placeholder text..."></p>
</body>
</html>

The above code works. But when I tried to add a br tag inside the p tag like <p data-text="placeholder text..."><br></p>, it does not work.

This line p br:only-child:not(:focus):before is the problem I think but I can’t find the solution for this. Can someone give me an advice?

>Solution :

You can add :has pseudoclass to your styles to fix:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Test</title>
  <style>
    p:empty:not(:focus):before,
    p:has(br:only-child):not(:focus):before {
        content: attr(data-text);
    }

  </style>
</head>
<body>
<p data-text="placeholder text..."><br></p>
</body>
</html>

Leave a Reply