【问题标题】:CSS Only: Use Multiple CSS Pseudo Classes Selectors [duplicate]仅 CSS:使用多个 CSS 伪类选择器 [重复]
【发布时间】:2018-05-06 03:07:24
【问题描述】:

我正在寻找一种纯 CSS 的解决方案来识别以下交叉点的第一个元素:

  • 每 5 个子弹性元素
  • 空填充元素

CodePen 示例: 请先阅读我的示例https://codepen.io/anon/pen/aqXyPP

我在这里的尝试不起作用。

.flex-element:nth-child(5n).empty-filler:first-child {
  font-weight: bold;
  font-style: italic;
}

但是,如果我删除伪类选择器:first-child,我会接近我的解决方案,但是,15 也被错误地选择了。

问题 1) 如何更改我的 CSS 选择器以实现我的目标?虽然我可以更改我的 CSS 和 HTML 结构,但我无法在我的 HTML 标记中引入新的 CSS 类。

问题 2) 我可以同时使用 :nth-child():first-child 吗?

【问题讨论】:

  • nth-childfirst-child 都不关心类名。

标签: html css css-selectors pseudo-class


【解决方案1】:

你不能真正 :first-child 一个类,但你可以通过使用通用兄弟组合器将所有选定元素(但第一个元素除外)重置为原始值来解决这个问题

/* select every fifth item that's also .empty-filler
/* this should select 10 and 15 */
.flex-element:nth-child(5n).empty-filler{
  color: red
}

/* resets siblings to original value, which leaves only the first highlighted. 
/* In this case resets the 15, leaving only 10 as red*/
.flex-element:nth-child(5n).empty-filler ~ .flex-element:nth-child(5n).empty-filler{
  color:black;    
}

* {
  box-sizing: border-box;
}

.content {
  padding: 8px;
  border: 1px solid lightgrey;
}

.flex-container {
  display: flex;
  flex-wrap: wrap;
  width: 500px;
}

.flex-element {
  border: 1px solid black;
  width: 100px;
  height: 50px;
  padding: 4px;
  font-size: 24px;
}

.filled {
  background: #bbb;
}

.empty-filler {
  background: #eee;
}
<div class="content">
  <div class="flex-container">
    <div class="flex-element filled">1</div>
    <div class="flex-element filled">2</div>
    <div class="flex-element filled">3</div>
    <div class="flex-element filled">4</div>
    <div class="flex-element filled">5</div>
    <div class="flex-element filled">6</div>
    <div class="flex-element filled">7</div>
    <div class="flex-element filled">8</div>
    <div class="flex-element empty-filler">9</div>
    <div class="flex-element empty-filler">10</div>
    <div class="flex-element empty-filler">11</div>
    <div class="flex-element empty-filler">12</div>
    <div class="flex-element empty-filler">13</div>
    <div class="flex-element empty-filler">14</div>
    <div class="flex-element empty-filler">15</div>
    <div class="flex-element empty-filler">16</div>
  </div>
<div>

上面的代码选择所有 5 的倍数(所以所有第 5 列)+ .empty-filler(在本例中为 10 和 15)的项目并将它们变为红色。

然后是使用 ~ 通用兄弟组合器来重置任何匹配元素上的原始值,该元素具有与条件匹配的先前兄弟,因此它将 15 定位为黑色,并将 10 保留为红色,因为它没有以前的兄弟姐妹符合条件。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-06-20
    • 2012-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-11
    相关资源
    最近更新 更多