css - 有没有办法选择带有类的特定元素?

标签 css

我需要将特定样式仅应用于类的特定实例。

所以...假设我的 html 中有以下内容:

<div class="dog">Text</div>
<div class="dog">More text</div>
<div class="dog">Even more text</div>

是否有选择器或其他东西可以用来对带有“dog”类的第二个 div 应用轻微的变化,而不是其他两个 div?

提前致谢!

最佳答案

您可以使用 :nth-child() 选择器。

.dog:nth-child(2) {
  color: red;
}
<div class="dog">Text</div>
<div class="dog">More text</div>
<div class="dog">Even more text</div>


如果你想选择所有 .dog 类的 div,但是第一个和最后一个 div 你可以组合 : not():first-of-type:last-of-type 选择器(.dog:not(:first-of- type):not(:last-of-type)).

.dog:not(:first-of-type):not(:last-of-type) {
  color: red;
}
<div class="dog">Text</div>
<div class="dog">More text</div>
<div class="dog">Even more text</div>
<div class="dog">Text</div>
<div class="dog">More text</div>
<div class="dog">Even more text</div>
<div class="dog">Text</div>
<div class="dog">More text</div>
<div class="dog">Even more text</div>

关于css - 有没有办法选择带有类的特定元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27663772/

相关文章:

html - 背景图片在移动设备下方留下空白

css - 如何在没有纵横比的 SVG 中保持图像的纵横比

javascript - 单击按钮时应用 Css

html - @fontface 可以在标签中使用吗? (为了电子邮件签名的可靠性)

html - 点领导者跨越过多的线

html - 文本框内的图标 html css

jquery - 在 Internet Explorer 9 中使用 jQuery 为子项设置动画时父 div 投影错误

jquery - 水平到带有初始屏幕的 Canvas 外导航,绝对定位冲突

html - 如何水平居中DIV

javascript - 带有 HTML 的图片下载按钮不起作用