【问题标题】:How to change the color of specific text inside of a paragraph with only a class selector?如何仅使用类选择器更改段落内特定文本的颜色?
【发布时间】:2014-09-18 19:30:59
【问题描述】:

我正在学习一些 CSS,我遇到的问题之一就是这个。

我已经看到了这个 html,我应该编写 CSS 来强调(红色表示辛辣,绿色表示素食),同时强调强烈标记的素食和辛辣菜单项以及它们的描述符(强标签中的“素食”和“辣!!!”)。通过编写包含在 html 下的 css,我对描述符有一些运气,但我似乎找不到允许我将它们分开的选择器组合。在不包括非素食/非辣味选项的情况下,我还没有在菜单项的标题上取得任何成功。我应该提到,一切都必须使用 CSS 2.0 来完成。如果有人有一些见识,我将不胜感激!

开胃菜

  <p>
     <strong>Mozzarella Sticks</strong><br />
     Golden fried and served with marinara sauce. - $7.49<br />
  </p>

  <p>
     <strong>Spicy Buffalo Wings</strong><br />
     An American classic with a kick! Grilled to perfection
     and tossed in the hottest sauce we got! - $8.99<br />
     <strong>Spicy!!!</strong>
  </p>

  <p>
     <strong>Crab Wontons</strong><br />
     Crab, cream cheese, scallions, bell peppers. - $6.99
  </p>

  <p>
     <strong>Vegetable Spring Rolls</strong><br />
     Cabbage, ginger, carrots, celery, scallions, onions,
     black mushrooms, glass noodles, rolled in a crispy
     wrapper. - $6.99<br />
     <strong>Vegetarian</strong>
  </p>

  <p>
     <strong>Nachos</strong><br />
     Creamy white queso blended with fresh tomatoes,
     red onion, cilantro and roasted poblanos. Served
     with warm tortilla chips. - $6.99
  </p>

  <p>
     <strong>Edamame</strong><br />
     Salted soybeans in the pod. - $5.99<br />
     <strong>Vegetarian</strong>
  </p>

到目前为止,这是我的 CSS

    div#appetizers br + strong
{
color:red;
}

【问题讨论】:

  • CSS 无法检测元素的内容,只能检测其在 DOM 中的位置和层次结构。要做到听起来像你想要的,你要么必须改进你的 HTML 结构,并以不同的、独特的结构构建素食与辛辣的条目(因此绕过文本检测,依赖于你的选择器的文档结构),或者,javascript 可以检查取出一个元素,解析文本,并应用一些样式。但应该注意的是,您不能将样式应用于元素内容的 part。为了让“辣”这个词变成红色,它需要被包裹在一个标签中,在&lt;strong&gt;内。
  • 如果可以的话,我会这样做,但这样做的要求是没有 html 编辑(为我提供的 html)以及没有 javascript。这必须完全使用 CSS 选择器来完成。
  • 如果这是工作的要求,我会说提供的html不够好。标记至少应该区分蔬菜和辛辣,以使这项工作在没有 javascript 或 css3 的情况下工作。我知道这不能回答你的问题,但我觉得很奇怪。是否为浏览器支持设置了这些要求?如果您多解释一下,也许有办法解决它。

标签: css xhtml strict


【解决方案1】:

使用:nth-of-type() 方法来表示您要定位的&lt;p&gt; 元素。 但是你只能使用css2 ...没关系。使用类似于这个例子的 css2 版本:

在 css3 中:ol &gt; li:nth-child(3) == css2:ol &gt; li:first-child + li + li

试试你的&lt;p&gt;(假设你知道你提供的 html 的包含元素) 比如#somedivID &gt; p:first-child + p strong {color:red;}

【讨论】:

  • 这只适用于永不改变的静态页面。
  • Static 非常适合我,因为这是一个菜单模型,不需要任何更改!谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-05
  • 2012-04-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多