htmlcss

Cannot create text underline using css that matches my design


I am trying to create this UI from a design file and cannot get it to exactly match. I can create something similar but the underline has padding before/after each line that I am unable to replicate. As the text spans more lines, the underline show extend before/after for each line.

The text content comes from a CMS, so I have no control over where the line breaks occur. The solution also needs to work in a responsive layout.

design file UI example

I've created something similar using text-decoration properties but it is a little off.The "underline" should extend a little beyond the text on each line.

div {
  background:#09333c;
  padding: 2rem;
  max-width: 275px;
}

p {
  color: white;
  font-size: xx-large;
  font-weight: bold;
  text-decoration: underline;
  text-align: center;
  text-decoration-thickness: 0.3em;
  text-underline-offset: -0.2em;
  text-decoration-skip-ink: none;
  text-decoration-color: #20a9b3;
}
<div>
  <p>Lorem ipsum dolor amet</p>
</div>


Solution

  • If you just want a solid underline under the text, and don't need any text-decoration-skip-ink behavior - then you can achieve this by using a linear gradient background for the underline, in combination with a bit of side padding and box-decoration-break: clone; on an line element. (I inserted a span here; your CMS would have to allow you to insert at least that then via the template for this piece of content or something, even if you can't specifically control what the individual text content would be in each instance.)

    div {
      background:#09333c;
      padding: 2rem;
      max-width: 275px;
    }
    
    p {
      color: white;
      font-size: xx-large;
      font-weight: bold;
      text-align: center;
    }
    
    p span {
      padding: 0 .5em;
      -webkit-box-decoration-break: clone;
      box-decoration-break: clone;
      background-image: linear-gradient(
        to right,
        #20a9b3,
        #20a9b3
      ); /* Define your gradient colors */
      background-position: 0% 100%; /* Start the gradient at the bottom */
      background-size: 100% .5em; /* Set the size and thickness of the underline */
      background-repeat: no-repeat; /* Ensure the gradient doesn't repeat */
    }
    <div>
      <p><span>Lorem ipsum dolor amet</span></p>
    </div>