CSS中#testid.testclass与#testid .testclass的区别

在一些面试中常常会考到一些很奇怪但又比较基础的问题,就如本文所要讲述的css选择器使用上的一个细节。

如下css和html代码,你能说出哪块是啥颜色吗?(如果你看一眼就知道了,那么请随意~)

        <style>
            #testid.testclass{
                background: red;
            }
            #testid .testclass{
                background: green;
            }
        </style>
    <div id="testid" class="testclass" style="width:200px;height:200px;margin:0;">
        <div class="testclass" style="width:100px;height:100px;margin:10px auto"></div></div>


口说无凭,咱们程序员都是以实际测试为主,如下显示效果(其他html无关代码略)

对于#testid.testclass与#testid .testclass的区别,在我学习css的道路上并未遇到过,可能是因为我学的乱吧,但回头看看,自己琢磨下也是可以找到啥区别的,只是缺乏官方的解释(这个解释有空我去找找<偷懒了>,已经补充部分,见本文补充<文章末尾>)。

 

时间不多了,下面直接说下我的理解吧。

首先#testid.testclass,在id后紧跟点号和class的写法,那么表示是匹配id为testid的元素中再匹配class是testclass的元素。

最后#testid .testclass,在id后加空格然后跟上点号和class的写法,那表示匹配id为testid的元素,然后再在该元素的子孙元素中匹配class是testclass的元素。

 

PS:上面的#testid可以是其他如div标签、class(class前面要加点号哦,这个可是比较特殊的),其他变种的情况大家自己琢磨吧!!!

PPS:最后我还联想到,除了#testid .testclass中的空格所代表的子孙关系,还有~表示的兄弟关系、+表示的相邻兄弟关系、>表示的子元素关系。

 

补充:关于官方文档对这方面的一些说明(摘自:http://www.w3.org/TR/2011/REC-css3-selectors-20110929/)

PatternMeaningDescribedFirst defined in CSS level
E Fan F element descendant of an E elementDescendant combinator1
E > Fan F element child of an E elementChild combinator2
E + Fan F element immediately preceded by an E elementAdjacent sibling combinator2
E ~ Fan F element preceded by an E elementGeneral sibling combinator3

类选择器的使用:

CSS examples:

We can assign style information to all elements with class~="pastoral" as follows:

*.pastoral { color: green }  /* all elements with class~=pastoral */

or just

.pastoral { color: green }  /* all elements with class~=pastoral */

The following assigns style only to H1 elements with class~="pastoral":

H1.pastoral { color: green }  /* H1 elements with class~=pastoral */

Given these rules, the first H1 instance below would not have green text, while the second would:

<H1>Not green</H1>
<H1 class="pastoral">Very green</H1>

The following rule matches any P element whose class attribute has been assigned a list of whitespace-separated values that includes both pastoral and marine:

p.pastoral.marine { color: green }

This rule matches when class="pastoral blue aqua marine" but does not match for class="pastoral blue".

转载于:https://www.cnblogs.com/yevon/archive/2013/03/29/2987068.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值