1

I am trying to add guitar chords above text, just like in this question. While that technique works in most cases, I would like to extend it to also work in the following situation, where the chords overlap:

p {
 margin-top:50px;
}
span.chunk {
 position:relative;
}
span.chunk:before {
  content:attr(data-chord);
  position:absolute;
  top:-15px;
}
<p>
As
<span class="chunk" data-chord="C">I was going over the</span> 
<span class="chunk" data-chord="Am">f</span>
<span class="chunk" data-chord="B">ar</span>
</p>

The end result should simply push the whole chunk over, like this:

enter image description here

Is there a way I can accomplish this, preferably using just CSS?

Daniel Centore
  • 3,220
  • 1
  • 18
  • 39

2 Answers2

4

Here is an idea using flexbox. The trick is to make the span an inline-flex container with a column direction so we keep the pseudo-element in-flow; thus it will affect the width of the container.

The widest one between the current content and the pseudo element will define the width.

p {
  margin-top: 50px;
}

span.chunk {
  position: relative;
  display: inline-flex;
  flex-direction: column;
  vertical-align: bottom; /*This is mandatory to keep the text without chunk in the bottom*/
}

span.chunk:before {
  content: attr(data-chord);
  position: relative;
}
<p>
  As
  <span class="chunk" data-chord="CCC">I was going over the</span>
  <span class="chunk" data-chord="Am a long text">f</span> 
  more text here
  <span class="chunk" data-chord="BB">ar</span>
</p>
Temani Afif
  • 245,468
  • 26
  • 309
  • 415
  • @sol yes too slow :p by the way you had a small issue by adding flex to the `p`, you will break the copy paste of text. it's was the issue of his old question btw .... and I suppose you already saw the featured question for this issue : https://stackoverflow.com/questions/27970957/flexbox-adding-newline-to-clipboard – Temani Afif May 15 '18 at 21:39
0

You can use :after pseudo-element and position:relative instead.

p {
 margin-top:50px;
}
span.chunk {
 position:relative;
}
span.chunk:after {
  content:attr(data-chord);
  position:relative;
  margin-left: -1ex;
  top:-15px;
}
<p>
As
<span class="chunk" data-chord="C">I was going over the</span> 
<span class="chunk" data-chord="Am">f</span>
<span class="chunk" data-chord="B">ar</span>
</p>
Amr Noman
  • 2,597
  • 13
  • 24