skip to Main Content

In my statically generated site, I have a list of links with parenthetical explanations, with entries like

When I run a code formatter on the source HTML, it looks something like the first example in the code below: There is a line break at the end of the link text. Unfortunately, this causes the whitespace to be associated with the link text instead of the <span> element containing the parenthetical explanation.

As a result, the underline indicating the link extends over the space, which looks bad. In the second link, I fix this problem by modifying the source so that there is no line break before </a>, but this results in inconsistent code formatting and is easy to break if I forget to disable formatting in my IDE. Here is a screenshot from Firefox 130.0.1:

enter image description here

And here is the source:

<p>
  <a href="https://example.com">
        This link looks weird because the whitespace is associated with it
      </a>
  <span>
        (explanation)
      </span>
</p>
<p>
  <a href="https://example.com">
        This link looks as desired, but only because of how I formatted the
        source HTML</a>
  <span>
        (explanation)
      </span>
</p>

Is there a way to force the whitespace out of the </a> tag that is robust to HTML formatting, e.g. using CSS?

2

Answers


  1. Try this,

    p {
      max-width: 100%;
      display: flex;
      gap: 8px; /* adjust as pleased */
      flex-wrap: nowrap;
    }
    a {
      text-overflow: ellipsis;
      white-space: nowrap;
      overflow: hidden;
    }
    <!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="UTF-8">
      </head>
      <body>
        <p>
          <a href="https://example.com">
            This link looks weird because the whitespace is associated with it
          </a>
          <span>
            (explanation)
          </span>
        </p>
        <p>
          <a href="https://example.com">
            This link looks as desired, but only because of how I formatted the
            source HTML</a>
          <span>
            (explanation)
          </span>
        </p>
      </body>
    </html>
    Login or Signup to reply.
  2. HTML can be a bit finicky like that. This is the only solution I could find.

    a {
      display: inline-block;
    }
    <p>
      <a href="stackoverflow.com">
        Run.
      </a>
      <span>(Explanation)</span>
    </p>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search