什么时候使用CSS类和什么时候不? [英] When to use CSS classes and when to not?

查看:164
本文介绍了什么时候使用CSS类和什么时候不?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

何时应该向元素添加类并使用类选择器对其进行样式化,应该何时在父类上添加类/ id,并使用元素?



示例:

 < div class =warning-dialog> 
< h3>这是标题< / h3>
< p>这是消息< / p>
< / div>

.warning-dialog {}
.warning-dialog h3 {}
.warning-dialog p {}

vs。

 < div class =warning-dialog> 
< h3 class =warning-title>这是标题< / h3>
< p class =warning-message>这是讯息< / p>
< / div>

.warning-dialog {}
.warning-title {}
.warning-message {}

或应该执行

  .warning-dialog .warning-dialog { } 
.warning-dialog .warning-title {}
.warning-dialog .warning-message {}

$ b $问自己这个简单的问题:


全部<$>

c $ c>< x> 这个共同祖先下的元素意味着相同的东西?


答案是肯定的,那么你不需要在这些元素上的类名。以您的代码为例,以下是足够的:

 < div class =warning-dialog> 
< h3>这是标题< / h3>
< p>这是消息< / p>
< / div>

因为 .warning-dialog ,所有 h3 元素(1)和所有 p 元素(1)将意味着相同,标题和内容的对话框!意思是,你不需要在它们上面有任何特定的类名,并且可以通过 .warning-dialog h3 .warning-dialog



但是,如果上述问题的答案是否,那就是一个完全不同的故事:

 < div>警告< / div> 
< div>信息< / div>
< div>错误< / div>

您不能(容易)使用CSS指定每个div,

 < div class =warning-dialog>警告< / div> 
< div class =info-dialog>信息< / div>
< div class =error-dialog>错误< / div>


When should you add classes to elements and style them using class selectors and when should you instead add a class/id on the parent and use the elements just as is?

Example:

<div class="warning-dialog">
    <h3>This is the title</h3>
    <p>This is the message</p>
</div>

.warning-dialog {}
.warning-dialog h3 {}
.warning-dialog p {}

vs.

<div class="warning-dialog">
    <h3 class="warning-title">This is the title</h3>
    <p class="warning-message">This is the message</p>
</div>

.warning-dialog {}
.warning-title {}
.warning-message {}

Or should you do

.warning-dialog .warning-dialog {}
.warning-dialog .warning-title {}
.warning-dialog .warning-message {}

解决方案

Ask yourself this simple question:

Do all <x> elements under this common ancestor mean the same thing?

If the answer to that is yes, then you don't need a class name on those elements. Taking your code as an example, the following is sufficient:

<div class="warning-dialog">
    <h3>This is the title</h3>
    <p>This is the message</p>
</div>

Because inside of a .warning-dialog, all h3 elements (1) and all p elements (1) would mean the same, the title and the content of the dialog! Meaning, you don't need to have any specific class names on them and they are easily accessible via .warning-dialog h3 or .warning-dialog p.

If however, the answer to above question is "No", that's a whole different story:

<div>Warning</div>
<div>Info</div>
<div>Error</div>

You can't (easily) designate each div with a CSS, they don't all mean the same thing, so you need to use class names to make it better!

<div class="warning-dialog">Warning</div>
<div class="info-dialog">Info</div>
<div class="error-dialog">Error</div>

这篇关于什么时候使用CSS类和什么时候不?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆