Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading