使选择器有助于元素宽度 [英] Make selector contribute to element width

查看:135
本文介绍了使选择器有助于元素宽度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在文本上添加吉他和弦,就像在



有没有办法可以做到这一点,最好只使用CSS?

解决方案

这是一个使用flexbox的想法。诀窍是使列宽为 inline-flex 容器的列方向,以便让伪元素保持流动状态;因此会影响容器的宽度。

当前内容和伪元素之间最宽的宽度将定义宽度。

  p {margin-top:50px;} span.chunk {position:relative;显示:inline-flex; flex-direction:列; vertical-align:bottom; / *这是强制性的,以保持在底部没有块的文本* /} span.chunk:before {content:attr(data-chord); position:relative;}  

< p>由于< span class =chunkdata-chord =CCC>我正在检查< / span> < span class =chunkdata-chord =是长文本> f< / span>这里有更多文字< span class =chunkdata-chord =BB> ar< / span>< / p>


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:

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

解决方案

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>

这篇关于使选择器有助于元素宽度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆