选择器、伪类、伪类选择器

参考W3C手册:http://www.w3school.com.cn/cssref/css_selectors.asp
 
选择器:
*{...} //通配符选择器,通常用来设置全局统一的样式
body html div ul ... //元素选择器,会统一修改该层级以及该层级如下的全部相同的元素
.box //类名选择器
#father //ID选择器
#father>div //选择父元素id是father 的全部div元素 (只选择一代)
#father div //选择父元素id是father 的全部div元素 (全部的后代元素)
...
 
伪类:(选择器 后面接 一个 冒号 的是伪类)
  伪类实际上是弥补了CSS选择器的不足,用来更方便地获取信息。
  dom:
<div id="father">
    <div class="box"></div>
    <p></p>
</div>
 
  css:
.box:hover
.box::after{ //在元素以后添加内容。 css2
  content: " " //伪类没显示,加上这个属性。以后就正常写样式。
}
.box::before //在元素以前添加内容。 css2 .box:first-letter //向文本的第一个字母添加特殊样式 css1 .box:first-line //向文本的首行添加特殊样式 css1 .box:first-child //#father 下的第一个 class叫box的元素 css2 p:last-child //选择属于其父元素最后一个子元素每一个 <p> 元素。 css3 p:only-child //选择属于其父元素的惟一子元素的每一个 <p> 元素。 css3 p:first-of-type // 选择属于其父元素的首个 <p> 元素的每一个 <p> 元素。 css3 .box:nth-child(odd) // 等同于 nth-child(2n+1) 奇数行 .box:nth-child(even) // 等同于 nth-child(2n) 偶数行 ...//更多请参考第一行的连接

 

伪类选择器:(选择器 后面接 两个 冒号 的是伪类选择器)
  而伪元素本质上是建立了一个虚拟容器(元素),咱们能够在其中添加内容或样式。
ul::-webkit-scrollbar{...} //设置滚动条的样式
...

 

 

:before,after和其余伪元素添加

 
div:nth-of-type(2)::before{
/*必须添加content属性,不然后期不可见*/
content: "";
/*默认是行级元素,若是想设置宽高,就必须转换为块级元素*/
position: absolute;
width: 20px;
height: 20px;

border-radius: 10px;
left: -10px;
top: -10px;
}
div:nth-of-type(2)::after{
/*必须添加content属性,不然后期不可见*/
content: "";
/*默认是行级元素,若是想设置宽高,就必须转换为块级元素*/
position: absolute;
width: 20px;
height: 20px;

border-radius: 10px;
left: -10px;
bottom: -10px;
}



/*获取第一个字符:实现首字下沉*/
p::first-letter{
color: red;
font-size: 30px;
float: left;/*文本环绕*/
}

/*获取第一行内容:若是设置了::first-letter,那么没法同时设置它的样式*/
p::first-line{
text-decoration: underline;
}

/*设置当前选中内容的样式*/
p::selection{

color: red;
/*它只能设置显示的样式,而不能设置内容大小*/
/*font-size: 30px;*/
}


  

在CSS中总有一些你不用不知道,用到才知道的“坑”。好比今天要谈的,把 before, after 伪类用在 <img> 标签上。css

嗯,实际上你用你会发现,在大多数浏览器这是无效的,dom中并不会出现你想要的结果。html

为何会这样呢?
让咱们回归到 W3C 标准中寻觅一下,在标准中,before, after 伪类的定义如:
css3

As their names indicate, the :before and :after pseudo-elements specify the location of content before and after an element's document tree content.
来自 https://www.w3.org/TR/CSS21/generate.html#before-after-content
web

咱们应该注意到所谓 document tree content,对于 img 这种自闭和标签,彷佛不存在 content (内容或后代元素)在标签中,因此选择器没有生效。但这样的解释还不够清晰,实际上标准中还有一行注释:浏览器

Note. This specification does not fully define the interaction of :before and :after with replaced elements (such as IMG in HTML). This will be defined in more detail in a future specification.dom

嗯,这回清楚了,对于可替换元素(如 img、input、select 等),标准并无清晰定义,这也致使了浏览器实现的差别性。post

相关文章
相关标签/搜索