选择具有特定元素的后代的父元素(:has)的方法是:

huangapple go评论56阅读模式
英文:

How to select an element with a parent that has a following parent with a specific element? (:has)

问题

I am trying to select an element ".cell-rich" which has a ".parent," but only when it's before another ".parent" which has an element ".cell-featured." I was hoping this would work, but it doesn't. Does anyone know if this is even possible with CSS without adding any additional classname to the parent container?

Example HTML:

So based on this example, I only wish to set padding-bottom: 0; to the 2nd parent's ".cell-rich" element.

EDIT:

As I was messing around and checking with browser dev tools, I noticed that using:

.parent:has(.cell-rich) + .parent:has(.cell-featured) {
padding-bottom: 0;
}

Actually applies the property to the .parent:has(.cell-featured) and not .parent:has(.cell-rich).

英文:

I am trying to select an element ".cell-rich". Which has a ".parent", but only when it's before another ".parent" which has an element ".cell-featured". I was hoping this would work, but it doesn't. Does anyone know if this is even possible with CSS without adding any additional classname to the parent container?

.parent:has(.cell-rich) + .parent:has(.cell-featured) > .cell-rich {
  padding-bottom: 0;
}

Example HTML:

<div class="parent">
  <div class="cell-rich"></div>
</div>
<div class="parent">
  <div class="cell-rich"></div>
</div>
<div class="parent">
  <div class="cell-featured"></div>
</div>
<div class="parent">
  <div class="cell-rich"></div>
</div>

So based on this example i only wish to set padding-bottom: 0; to the 2nd parent's ".cell-rich" element.

EDIT:

As i was messing around and checking with browser dev tools i noticed that using:

.parent:has(.cell-rich) + .parent:has(.cell-featured)
  padding-bottom: 0;
}

-- actually applies the property to the .parent:has(.cell-featured) and not .parent:has(.cell-rich).

答案1

得分: 0

CSS中没有选择前一个兄弟元素的方法,例如.parent.cell-rich。通过+、~运算符,你只能选择下一个兄弟元素。如果不想添加额外的类名,可以尝试使用JS来实现。

英文:

There is no way to select previous siblings e.g. .parent.cell-rich in CSS. With +,~ operators you can only select next sibling/s. If you don't want to add extra classnames, you can try using JS to achieve that.

huangapple
  • 本文由 发表于 2023年4月19日 19:28:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/76053954.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定