【问题标题】:How to target a specific text in the span with css如何使用 css 定位跨度中的特定文本
【发布时间】:2020-01-28 16:58:53
【问题描述】:

我有一个html:

<div class="test>

<span>Yellow</span>
<span>Blue</span>
<span>Purple</span>

</div>

我想要隐藏包含文本“黄色”和“紫色”的跨度。我可以用 CSS 做吗?也许属性? Span 没有类,或者换句话说,它们没有类。

【问题讨论】:

标签: html css text attributes target


【解决方案1】:

您可以将类添加到您的跨度中:

.test {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 80vw;
  margin: 0 auto;
}

.test span {
  height: 20px;
  flex: 1;
  margin: 0 1rem;
  color: white;
  text-align: center;
}

.test span.purple {
  background: purple;
}

.test span.red {
  background: red;
}
<div class="test">
<span class="purple">purple</span>
<span class="red">red</span>
<span class="purple">purple</span>
<span class="red">red</span>
</div>

或者您可以使用 :nth-of-type 定位它们

 .test span:nth-of-type(1) {
     // this gets you the first one
 }

 .test span:nth-of-type(2) {
     // this gets you the second one
 }

等等

【讨论】:

  • 这只是一个简单的例子,实际上我必须将它应用于我无法控制 html 的动态内容。因此,带类的跨度不是选项。 :nth-of-type 也不是一个选项,因为例如,“Yellow”这个词可以排在第一位,也可以排在第二位。我的问题更多:我可以通过 css 定位一个特定的词(例如,“黄色”)吗?像 img[title="flower"] 之类的东西(在这种情况下,我的目标是标题为“flower”的图像)?
  • 啊,好的。我不知道仅通过 CSS 可以定位文本的任何功能。如果你可以访问 js/jquery,你可以使用 :contains stackoverflow.com/questions/7321896/jquery-find-element-by-text
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-14
  • 2019-01-16
相关资源
最近更新 更多