imovies
当前位置:首 页>> 百 宝 箱 >>DIV+CSS 学习心得<8>:分组,嵌套,伪类,伪元素

DIV+CSS 学习心得<8>:分组,嵌套,伪类,伪元素

  这次说的东东,基本是CSS样式里写法的一些细节和技巧问题了,因为我也只初学,也不一定说的就全是对的,具体问题具体对待,您还得自己研究之后消化了才行。
  样式相同的定义是可以分组的,下面例子中,两种写法效果是一模一样的,使用分组的方法可以简化css代码,只需要将不同的样式定义名称(官方叫selector选择器)用逗号(英文状态下的逗号)隔开。

h1{
color:green;
}
h2{
color:green;
}
p{
color:green;
}


h1,h2,p{
color:green;
}

  当然,分组也有不好的地方,如果你后来只想修改其中的一个,那不是麻烦了,所以还是看实际应用情况,这里只是告诉你有这么一种可以分组的写法。
  然后是样式定义的嵌套,英文说法是Nesting Selectors,我英文不是很好,不知道这个Nesting(nest是巢的意思)在这里该翻译成什么好,所以我理解就是嵌套吧,或者叫级联?。官方解释是可以给一个选择器(比如A)内的选择器(B)定义样式,这样的话,在A作用的元素中如果出现了B所定义的元素,那这个元素就只使用B定义的样式,看例子,说的有些拗口,容易绕晕:

p{
color:blue;
text-align:center;
}
.marked{
background-color:blue;
}
.marked p{
color:white;
}

  上面的css样式定义,第一个定义了所有p这个元素的样式为文字颜色蓝色,文字居中显示,marked这个class定义了元素的背景色是蓝色,.marked p则表示:如果p元素的父级元素的样式如果是.marked,那么这个p元素内的文字颜色就是白色,会脱离第一个p的样式定义。这第三个.marked p的写法就是Nesting Selectors,自己有时间在DW里写好可以测试一下具体是怎么玩的。
  Pseudo-classes,直译就是伪类,我也没搞明白这个伪到底是啥意思。假的?冒充的?忽悠用的?What ever!下面是伪类的语法:

selector:pseudo-class {property:value;}
selector.class:pseudo-class {property:value;}

下面是咱能用的伪类的列表:

Pseudo name    Description
:active        Adds a style to an element that is activated 
:first-child        Adds a style to an element that is the first child of another element
:focus        Adds a style to an element that has keyboard input focus
:hover        Adds a style to an element when you mouse over it
:lang        Adds a style to an element with a specific lang attribute
:link            Adds a style to an unvisited link
:visited        Adds a style to a visited link

  咱们用的最多的伪类估计就是给链接定义四个不同状态样式的时候了,其他的用的不多。你可以给其他HTML元素,比如DIV,定义一个:hover的样式试试看,很给力哦。
  Pseudo-elements,直译就是伪元素,同上,不是很明白。下面是伪元素的语法:

selector:pseudo-element {property:value;}
selector.class:pseudo-element {property:value;}

下面是咱能用的伪元素的列表:

Pseudo name    Description
:after        Adds content after an element
:before        Adds content before an element
:first-letter    Adds a style to the first character of a text
:first-line        Adds a style to the first line of a text

  其中first-line只能作用于block级别的元素,能用的属性property有:

font properties
color properties 
background properties
word-spacing
letter-spacing
text-decoration
vertical-align
text-transform
line-height
clear

  其中first-letter也只能作用于block级别的元素,能用的属性property有:

font properties
color properties 
background properties
margin properties
padding properties
border properties
text-decoration
vertical-align (only if "float" is "none")
text-transform
line-height
float
clear

  :after和:before的写法如下,具体有啥效果,烦请自己准备好图片在DW里实验。

h1:before{
content:url(smiley.gif);
}

h1:after{
content:url(smiley.gif);
}

  这回就说到这里了,还是那句老话,我说的你不一定能看懂,还得靠你自己Google去研究,如果我理解错了,还麻烦您给指点一下,别让俺一错再错哦。
[Edit on 2011-2-11 0:06:21 By 笑傲江湖]
微信支付宝

标 签:CSSDIV

评 论0 引 用0 浏 览5518

上一篇DIV+CSS 学习心得<9>:Position和Float

下一篇[MOVIESHOW] Faster 极速复仇

说点什么:

正文内容:

 

图片博文

生日快乐

扫一扫分享之

人到穷途应一笑,几凡失意仍能傲。成败何须问江湖,我心依旧任逍遥。
这一生只想好好做个平凡的人,有个家有个梦,陪我迎接每一个早晨。
这一生只想好好做个平凡的人,何必争何必问,只有快乐开心才是真。