html - 段落中文本上方的位置跨度

标签 html css

我尝试将一些文本放在像这样的文本上方(用于音乐):

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

但我不想使用空格!
目前我有这个:

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>

这有效,但前提是我不触摸任何东西(字体大小...),因为底部值与字体大小值相同。

我想得到相同的结果,但没有那个限制。

你能帮帮我吗?

最佳答案

使用 top: -1em;移动 <span>取决于它自己的字体大小,因为 EM 是相对于当前元素的 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>

为了在文本换行时保持正确的垂直位置,我还建议在伪元素中显示文本,该伪元素位于与 span 换行的文本相关的位置。 ,而不是段落本身。

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>

关于html - 段落中文本上方的位置跨度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44482443/

相关文章:

css - Bootstrap 粘性页眉和页脚

html - 已应用背景 svg 图像但不可见

javascript - 以编程方式聚焦时不会出现焦点轮廓?

html - 浏览器无法识别字符串集 CSS 属性

css - 将多个 Assets 合并到单个文件

css - 在 Sails JS 0.10 中使用 Stylus

javascript - 如何跨浏览器调试网页渲染兼容性问题?

html - 摆脱默认的 html 标题样式?

javascript - 使用 CSS 或其他非 JS 方法模仿 "onselectstart=return false"?

javascript - 如何使 onChange 事件对来自数据库而不是来自用户操作 Jquery 的预选数据起作用