CSS选择器

注:代码部分,上面都是html,下面为css,如果放在.css文件中,就不用谢<style></style>,如果放在.html文件中,需放在<head></head>中。

1)类选择器——调用元素的class:

<div class="div1"></div>

<style>
 .div1 {margin:auto;}
<!--或者用下面的-->
div.div1 {margin:aotu;}
</style>

2)ID选择器——调用元素的id:

<div id="div2"></div>

<style>
#div2 {margin:10px;}
</style>

3)属性选择器——调用含某属性的某元素:

<a href="xx.html">会变颜色</a>
<a>不会变颜色</a>

<style>
a[href] {color:red;}
</style>

所有带有title属性的元素都会改变:

<a title="a">a</a>
<a title="b">b</a>

<style>
[title] {color:red;}
/**/
*[title] {color:red;}
</style>

还可以指定包含特定具体属性值的元素:title="a"的会变成红色字

<a title="a">a</a>
<a title="b">b</a>

<style>
[title="a"] {color:red;}
/**/
*[title="a"] {color:red;}
</style>

根据部分属性值选择:

<a title="a b">a</a>
<a title="b">b</a>

<style>
[title~="a"] {color:red;}
/**/
*[title~="a"] {color:red;}
</style>

4)子串匹配属性选择器

类型 描述
[href^="com"] 选择 abc 属性值以 "def" 开头的所有元素
[href$="com"] 选择 abc 属性值以 "def" 结尾的所有元素
[href*="com"] 选择 abc 属性值中包含子串 "def" 的所有元素
<a href="comb.com">blue</a>
<a href="baidu.com">green</a>
<a href="yahoo.com.cn">red</a>

<style>
    [href^="com"] {color:blue}
    [href$="com"] {color:green}
    [href*="com"] {color:red}
</style>

 5)后代选择器——调用某个元素内的元素

<div id="bg">
    <ul>
        <li>a</li>
        <li>b</li>
    </ul>
</div>

<style>
#bg ul{margin:10px;}
</style>

6)子元素选择器

  这里与后代选择器需要区分下,只有cd会变成红色:

<h1>ab<em>cd</em>ef</h1>
<h1>gh<b><em>ij</em></b>kl</h1>

<style>
    h1>em {color:red}
</style>

结合后代选择器、子选择器:www.baidu.com会变红

<div class="div1">
    <a href="www.baidu.com"><b>www.baidu.com</b></a>
    <a href="www.sina.com">www.sina.com</a>
</div>
<div class="div2"> <a href="www.baidu.com"><b>www.baidu.com</b></a> <a href="www.sina.com">www.sina.com</a> </div>

<style>
  div.div1 a > b {color:red}
</style>

7)相邻兄弟选择器

  注意的就是虽然是table+ul,但只有ul中的适用了样式,只从第二个兄弟开始变,第一个不变

<html>
<body>
  <table>...</table>
  <ul>...</ul>
</body>
</html>

<style>
html > body table + ul {margin-top:20px;}
</style>
原文地址:https://www.cnblogs.com/heyuheitong/p/4024870.html