Bootstrap-sass研究---预备篇:css选择器

周末在家研究了一下bootstrap-sass 的源代码,发现自己对于选择器还不是很明白。 做了一些笔记和大家分享。

1. ^ => start with

1
2
3
a[href^="http://"] {
    color: green;
}

a[href^="http://"]的意思就是:如果html中有a[href=… ]这样的元素,并且href后是以http为开头,匹配它,然后你就可以针对其写专门的css.

但是这个有一点尴尬,有时候项目写的不是很注意的话,所有的link都可能是以http开头的,这时候基本就傻眼了,但是你可以做一些来防止这样的事情发生。

1
2
3
4
5
6
7
a[href^="http://"] {
    color: green;
}

a[href^="http://www.domain.com"], a[href^="http://domain.com"] {
    color: blue;
}

不过这样也不是很保险,因为https这个情况还没有被包含到。

当然更不能和a[hreflang|="en"]这里面的混起来,它匹配的是以 en开头并且跟着-的,比如en-US,en-BR,当然还有它自身en

2. $ => end with

1
2
3
4
a[href$=".pdf"] {
   background: url(../images/pdf.png) no-repeat center right;
   padding-right: 20px;
}

这个和上面相差不大,即是以该元素结尾。

3. * => contain with

1
2
3
div[class*="post-"] p {
    color: green;
}

*代表包含,如果你的class里面包含了post- ,比如说post-robin, css就会对它生效

当然这个我们还是比较熟悉的嘛,毕竟我们写了很多的css都是这样的

1
2
3
* {
   background-color: yellow;
}

这个选择器下的css对整个页面都会生效。

不过如果单单只是这种情况的话,其实之前提到的那个方法更合适一些,即 div[class|="post"]

4. ~

1
2
3
a[rel~="copyright"] {
 color: green;
}

这个是匹配的情况是当rel有很多的值,且值是用空格分割的,那么如果其中的一个值恰好是copyright,那么就会成功


5 更多的

顺便梳理下其他必须用到的,大家都复习一下吧。

h2+p代表是拥有相同父亲元素的相邻元素,当然,它们必须是邻近的!
h2~p和 + 所代表意义几乎是一样的,但是不要求两者相邻。


1
2
3
.parent .child {//只要.parent的后代即可,孙子元素亦可
    background-color: red;
}
1
2
3
.one > .two {//必须是直接后代,否则不会生效
    background-color: red;
}
1
2
3
4
5
6
7
div[style] {  //匹配的是<div style="xxx">
    background-color: red;
}

input[type="text"] {  //匹配的是<input type="text">
    background-color: red;
}

伪类

1
2
3
4
5
6
7
8
a:link    /* unvisited links */
a:visited /* visited links */
a:hover   /* user hovers */
a:active  /* active links */
a:focus
a:focus:hover
p::first-line { text-transform: uppercase }
p::first-letter { color: green; font-size: 200% }

用于不同元素的变化,这个也很有用,可以不需要再用后台语言控制样式,而这个的用法也有很多变化,感兴趣可以去查文档。

1
2
3
4
tr:nth-child(2n+1) /* represents every odd row of an HTML table */
tr:nth-child(odd)  /* same */
tr:nth-child(2n+0) /* represents every even row of an HTML table */
tr:nth-child(even) /* same */

资料引用:
1. w3c.org selector
2. impressivewebs css sustring-macthing

Comments

Copyright © 2013 robinhwang Redesgin by RobinHwang