4

I have en element of text that contains a pseudo element to control the underline. What I want to achieve is when the element reaches two lines (or more), I want the underline to be 100 % width of the element, but now it only goes 100 % of the last row (see screenshot).

enter image description here

I've put up a fiddle to show you what I mean: https://jsfiddle.net/m6rmxuoy/1/

There are two examples: one with display: inline for the h2 element:

.wrapper {
  width: 260px;

  h2 {
    position: relative;
    display: inline;

    background-color: yellow;

    &:after {
      position: absolute;
      left: 0;
      bottom: 0;
      width: 80px;
      height: 3px;

      background-color: #0077bc;
      content: '';
    }

    &:hover:after {
      width: 100%;
    }
  }
}

The problem with this is that the width of the line in hover state doesn't fill up to the width of the first line.

The second try, with display: inline-block, adapts to the wrappers width instead of stopping at the longest line, as display: inline does:

.wrapper2 {
  width: 260px;

  h2 {
    position: relative;
    display: inline-block;

    background-color: yellow;

    &:after {
      position: absolute;
      left: 0;
      bottom: 0;
      width: 80px;
      height: 3px;

      background-color: #0077bc;
      content: '';
    }

    &:hover:after {
      width: 100%;
    }
  }
}

The result I want to achieve is this:

Hope to achieve this

I've googled for quite some time now, even found the box-decoration-break: clone;, but it doesn't help me with pseudo elements.

Any ideas?

Erik Blomqvist
  • 471
  • 1
  • 4
  • 16
  • Yeah...you can't do that...that's not the way the line-box model works. - https://stackoverflow.com/questions/37406353/make-container-shrink-to-fit-child-elements-as-they-wrap – Paulie_D Oct 10 '17 at 11:28
  • why not just wrap it into inline-block div with bottom border? – Karl Adler Oct 10 '17 at 11:38

2 Answers2

1

This isn't possible with just CSS, it's counter to how the browser renders CSS. The closest solution I could get was to add a line break in your text for wrapper2 (the inline-block example):

This text has too many<br>characters for 1 line

It's not ideal, but a more dynamic solution would require javascript, such as the one offered here: Shrink DIV to text that's wrapped to its max-width?

D-Money
  • 2,375
  • 13
  • 27
-1

i think remove the display property from the h2 tag will solve the issue, if i have understand your question.

    p {
        font-size: 18px;
        font-weight: normal;
        color: #fff;
        margin: 12px 0 0;
        position: relative;
        &:before {
            position: absolute;
            width: 100%;
            height: 2px;
            background: blue;
            content: '';
            display: none;
            bottom: 0;
        }
        &:hover:before {
            display: block;
        }
    }
Kaleem
  • 1