对于具有某个类的元素的选择器,如果它是一个&只有其父的孩子吗? [英] Selector for an element with certain class, if it is the one & only child of its parent?

查看:79
本文介绍了对于具有某个类的元素的选择器,如果它是一个&只有其父的孩子吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想对某个元素(具有某个类)应用某些CSS,如果它是一&只有其父级中的子级。我可以很容易地使用jQuery做到这一点,但我正在寻找一个纯CSS解决方案(适用于所有主流浏览器)。如何为这些元素写入选择器表达式?

I want to apply certain CSS to an element(with a certain class) if it is the one & only child within its parent. I can easily do this using jQuery but I'm looking for a pure CSS solution(that works across all major browsers). How do write selector expression for such elements ?

方案:

<div> 
   <span class='a1'/>
</div>

<div> 
   <a>random text</a>
   <span class='a1'/>
</div>

我想第一个 div code> .a1 元素,因为它是其父元素中唯一的元素。

I would like the first div contained .a1 element to be selected as it is the only element within its parent.

推荐答案

尝试使用Cross浏览器兼容性,

Try this for Cross browser compatibility,

.a1:first-child:last-child {
     color :red;
}

这篇关于对于具有某个类的元素的选择器,如果它是一个&只有其父的孩子吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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