Edwin ZAP
Edwin ZAP

Reputation: 463

Position Span above text in paragraph

I try to place some text above text like this (used in music):

     Am          E  
This is a new sentence  
     G            C  
This is another sentence  

but I don't want to use spaces!
Currently I have this:

p {
  position: relative;
  font-size: 50px;
}

span {
  position: absolute;
  bottom: 50px;
  color: red;
  font-size: 20px;
}
<div>
  <p>Test test test <span>Em</span>test test</p>
  <p>Test <span>Am</span>test test test test</p>
  <p>Test test test test <span>Am</span>test</p>
  <p><span>Am</span>Test test test test test</p>
</div>

That works but only if I don't touch anything (font-size...) because the bottom value is the same that the font-size value.

I would like to have the same result but without that constraint.

Can you help me please!?

Upvotes: 3

Views: 2000

Answers (1)

Ori Drori
Ori Drori

Reputation: 191946

Use top: -1em; to move the <span> up by it's own font size, since EM is relative to the current element's font-size:

p {
  position: relative;
  font-size: 50px;
}

span {
  position: absolute;
  top: -1em;
  color: red;
  font-size: 20px;
}
<div>
  <p>Test test test <span>Em</span>test test</p>
  <p>Test <span>Am</span>test test test test</p>
  <p>Test test test test <span>Am</span>test</p>
  <p><span>Am</span>Test test test test test</p>
</div>

To preserve the correct vertical position when the text wraps, I would also suggest displaying the text in a pseudo element, which is positioned in the relation to the text wrapped by thespan, and not the paragraph itself.

p {
  position: relative;
  font-size: 100px;
}

span {
  position: relative;
}

span::before {
  position: absolute;
  top: -0.5em;
  color: red;
  font-size: 0.4em;
  content: attr(data-text);
}
<div>
  <p>Test test test <span data-text="Em">test</span> test</p>
  <p>Test <span data-text="Am">test</span> test test test</p>
  <p>Test test test test <span data-text="Am">test</span></p>
  <p><span data-text="Am">Test</span> test test test test</p>
</div>

Upvotes: 3

Related Questions