2010-06-27 174 views
4

这些示例的最佳做法是什么?具体类名与类层次结构

1)

<style type="text/css"> 
.block .title {color:red} 
.anotherBlock .title {color:blue} 
</style> 
... 
<div class="block"> 
    <h3 class="title">SomeTitle</h3> 
</div> 
<div class="anotherBlock"> 
    <h3 class="title">anotherTitle</h3> 
</div> 
... 

2)

<style type="text/css"> 
.blockTitle {color:red} 
.anotherBlockTitle {color:blue} 
</style> 
... 
<div class="block"> 
    <h3 class="blockTitle">SomeTitle</h3> 
</div> 
<div class="anotherBlock"> 
    <h3 class="anotherBlockTitle">anotherTitle</h3> 
</div> 
... 

第一个代码看起来比较清爽,但它可以让别人认为H3标签将具有相同的样式属性。

回答

7
<style type="text/css"> 
.block h3 {color:red} 
.anotherBlock h3 {color:blue} 
</style> 
... 
<div class="block"> 
    <h3>SomeTitle</h3> 
</div> 
<div class="anotherBlock"> 
    <h3>anotherTitle</h3> 
</div> 

为什么?因为它与您的示例一样可读,但占用的代码更少=在用户浏览器中呈现的时间更少

+0

感谢关注我的问题。但我要求另外一件事。 抱歉没有足够的准确描述。 希望这会使我的问题清楚: 在这种情况下最好的方法是什么。从这两个实现中选择? – noxvile 2010-06-27 14:01:09

+0

(1) <风格类型= “文本/ CSS”> .block .showAllLinks {颜色:红色} .anotherBlock .showAllLinks {颜色:蓝}

noxvile 2010-06-27 14:01:28

+0

(2) <风格类型= “文/ CSS”> .blockShowAllLinks {颜色:红} .anotherBlockShowAllLinks {颜色:蓝}

noxvile 2010-06-27 14:02:03

1

仅当您需要从html标记本身的默认样式(如Eugene的示例)中分离时才使用类。尽可能使用继承,因为选择器越具体,就越有可能出现错误。