CSS 等价于 :has()
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29037763/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Css equivalent of :has()
提问by user3176519
In the following example:
在以下示例中:
<div class="section">
<div class="row">...</div>
<div class="row"> <- bottom margin here needs to be 0 ->
<div class="section">
<div class="row">...</div>
<div class="row">...</div>
</div>
</div>
</div>
.row {
margin-bottom:10px;
}
If div .row is parent of div .section reset bottom margin to 0.
如果 div .row 是 div .section 的父级,则将底部边距重置为 0。
I can do this with jquery, but is there a way to do it in css?
我可以用 jquery 做到这一点,但是有没有办法在 css 中做到这一点?
回答by Richard Parnaby-King
At the moment there is no way in CSS to select the parent element of another element.
目前,CSS 无法选择另一个元素的父元素。
However, in CSS4 there is the :has
pseudo-class - http://dev.w3.org/csswg/selectors-4/ :has
但是,在 CSS4 中有:has
伪类 - http://dev.w3.org/csswg/selectors-4/ :has
the following selector matches only elements that contain an child:
a:has(> img)
The following selector matches a element immediately followed by another element:
dt:has(+ dt)
The following selector matches elements that don't contain any heading elements:
section:not(:has(h1, h2, h3, h4, h5, h6))
Note that ordering matters in the above selector. Swapping the nesting of the two pseudo-classes, like:
section:has(:not(h1, h2, h3, h4, h5, h6))
...would result matching any element which contains anything that's not a header element.
以下选择器仅匹配包含子元素的元素:
a:has(> img)
以下选择器匹配紧跟另一个元素的元素:
dt:has(+ dt)
以下选择器匹配不包含任何标题元素的元素:
section:not(:has(h1, h2, h3, h4, h5, h6))
请注意,上述选择器中的排序很重要。交换两个伪类的嵌套,例如:
section:has(:not(h1, h2, h3, h4, h5, h6))
...将导致匹配包含任何不是标题元素的任何元素。
It looks like you may be using a recursive function to generate your sections/rows. Perhaps add a class to the row if it has sub-sections? Then you could target that class to apply margin-bottom to.
看起来您可能正在使用递归函数来生成您的部分/行。如果它有子部分,也许可以在行中添加一个类?然后你可以定位那个类来应用 margin-bottom 。
回答by Chris Herbert
You could do this by applying a negative margin
to the .section
element that's equivalent to the standard margin
of .row
element.
您可以通过施加负这样做margin
的.section
这相当于标准元素margin
的.row
元素。
.row {
margin-bottom: 20px;
}
.row > .section {
margin-top: -20px;
}