根据元素的子元素将CSS样式应用于元素 [英] Apply CSS styles to an element depending on its child elements

查看:130
本文介绍了根据元素的子元素将CSS样式应用于元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以为元素定义CSS样式,只有在匹配元素包含特定元素(作为直接子项目)时才应用?



注意:我试图设置父元素的样式 ,取决于它包含的子元素。

 < style> 
/ *注意这是无效的语法。我使用不存在的
:包含伪类来显示我想要实现的。 * /
div:包含div.a {border:solid 3px red; }
div:包含div.b {border:solid 3px blue; }
< / style>

<! - 下面的div应该有一个红色边框,因为
if包含一个div = class =a - >
< div>
< div class =a>< / div>
< / div>

<! - 以下div应该有一个蓝色边框 - >
< div>
< div class =b>< / div>
< / div>

注2 :我知道我可以使用javascript实现,只是想知道这是否可能使用一些未知(对我)的CSS功能。

解决方案

据我所知,基于子元素的父元素不是CSS的可用特征。



如果您可以执行 div [div.a] div:包含[div.a] ,但这是不可能的。



您可以考虑查看 jQuery 。它的选择器与包含类型工作非常好。您可以根据其子内容选择div,然后将css类应用到父类所有行。



如果使用jQuery,这可能会工作(未经测试,但理论存在):

  $('div:has(div.a)')。 css('border','1px solid red'); 

  $('div:has(div.a)')。addClass('redBorder'); 

结合css类别:

  .redBorder 
{
border:1px solid red;
}

这是 jQueryhasselector


Is it possible to define a CSS style for an element, that is only applied if the matching element contains a specific element (as the direct child item)?

I think this is best explained using an example.

Note: I'm trying to style the parent element, depending on what child elements it contains.

<style>
  /* note this is invalid syntax. I'm using the non-existing
   ":containing" pseudo-class to show what I want to achieve. */
  div:containing div.a { border: solid 3px red; }
  div:containing div.b { border: solid 3px blue; }
</style>

<!-- the following div should have a red border because
     if contains a div with class="a" -->
<div>
  <div class="a"></div>
</div>

<!-- the following div should have a blue border -->
<div>
  <div class="b"></div>
</div>

Note 2: I know I can achieve this using javascript, but I just wondered whether this is possible using some unknown (to me) CSS features.

解决方案

As far as I'm aware, styling a parent element based on the child element is not an available feature of CSS. You'll likely need scripting for this.

It'd be wonderful if you could do something like div[div.a] or div:containing[div.a] as you said, but this isn't possible.

You may want to consider looking at jQuery. It's selectors work very well with 'containing' types. You can select the div, based on its child contents and then apply a css class to the parent all in one line.

If you use jQuery, something along the lines of this would may work (untested but theory is there):

$('div:has(div.a)').css('border', '1px solid red');

or

$('div:has(div.a)').addClass('redBorder');

combined with css class:

.redBorder
{
    border: 1px solid red;
}

Here's the documentation for jQuery "has" selector.

这篇关于根据元素的子元素将CSS样式应用于元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆