当我们有一个唯一的父元素并且其中有一些不同的(不相关的)子元素时,哪种方式是定义和应用样式的首选方式?
#parentCon
{
declarations...
}
/* 1. Following is unnecessary, even looks somewhat weird
but it might give a clue about relation to developer. */
#parentCon #child1
{
declarations...
}
/* 2. Apply directly to child by its id.
They are defined consecutively so developer have a clue
about their relation, indentation will also help. */
#parentCon
{
declarations...
}
#child1
{
declarations...
}
/* 3. Use a class for child although child is unique,
there will be no other instances of it. */
#parentCon .child1
{
declarations...
}
<div id="parentCon">
<div id="child1">
</div>
<div id="child2">
</div>
</div>
<div id="parentCon">
<div class="child1">
</div>
<div class="child2">
</div>
</div>
虽然只有一个实例,但使用类选择器是否明智?使用类时浪费性能怎么办? 我正在尝试了解您在此处为 child 使用 ID 的用例想法,因此这与特定的亲子问题无关。
最佳答案
在这种情况下我不会考虑性能问题,浏览器在优化方面确实做得很好。
最大的区别在于可重用性。
如果该元素在文档中是唯一的,则使用 ID。如果您想重用样式,请使用类。
#parentCon #child1
不过很有趣。它可能看起来很奇怪,但具有一定的意义。仅当 #child1
是 #parentCon
的 child 时,才将此样式应用于 #child1
。如果您要动态生成页面并在页面中移动 #child1
可能是一个有趣的想法。
关于html - 子元素的 ID 选择器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30616133/