Why is the background sometimes displayed and sometimes not?

Viewed 63

I have CSS that underlines certain words.
Later I found that it didn't appear in the space.
I found that on the sample HTML, the underline is displayed between the upper example, but not between the lower example.
Why isn't the space below underlined?

<html>
  <head>
    <meta charset="utf-8" />
    <style>
      .correct-line {
        background: linear-gradient(transparent 55%, rgb(10, 150, 126) 60%);
      }
    </style>
  </head>
  <body>
    <p>example<span class="correct-line"> </span>example</p>
    <hr />
    <div>
      example
      <span class="correct-line"> </span>example
    </div>
  </body>
</html>

2 Answers

On your code, whitespace in span is ignored when compiling html codes. You need to use &nbsp; to represent the whitespace only.

<html>
  <head>
    <meta charset="utf-8" />
    <style>
      .correct-line {
        background: linear-gradient(transparent 55%, rgb(10, 150, 126) 60%);
      }
    </style>
  </head>
  <body>
    <p>example<span class="correct-line">&nbsp;</span>example</p>
    <hr />
    <div>
      example<span class="correct-line">&nbsp;</span>example
    </div>
  </body>
</html>

It's because CSS processes multiple whitespaces into single space and space after newline character are both considered whitespace and hence reduced to single whitespace and 2nd whitespace is deleted. Contrast your code to below.

<html>
  <head>
    <meta charset="utf-8" />
    <style>
      .correct-line {
        background: linear-gradient(transparent 55%, rgb(10, 150, 126) 60%);
      }
    </style>
  </head>
  <body>
    <p>example<span class="correct-line"> </span>example</p>
    <hr />
    <div>
      example<span class="correct-line"> </span>
example
    </div>
  </body>
</html>

Also checkout https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model/Whitespace for more info.

You can use &nbsp; if it's just your inserted data but presumably it's coming from a different source

You are probably better off using white-space:pre; as below

<html>
  <head>
    <meta charset="utf-8" />
    <style>
      .correct-line {
        background: linear-gradient(transparent 55%, rgb(10, 150, 126) 60%);
        white-space: pre;
      }
    </style>
  </head>
  <body>
    <p>example<span class="correct-line"> </span>example</p>
    <hr />
    <div>
      example
      <span class="correct-line"> </span>example
    </div>
    <div>
      example<span class="correct-line">
       </span>example
    </div>
  </body>
</html>

Related