Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
266 views
in Technique[技术] by (71.8m points)

javascript - Make selector contribute to element width

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>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...