html - 子元素的 ID 选择器

标签 html css css-selectors

当我们有一个唯一的父元素并且其中有一些不同的(不相关的)子元素时,哪种方式是定义和应用样式的首选方式?

#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/

相关文章:

javascript - 使用 jquery 删除 div

Jquery Datatable 根据值更改行颜色

html - 第一次按下下一个按钮时,jQuery 循环 slider 重叠

html - 加载到页面中间的 WordPress 页脚样式

ruby-on-rails - Capybara 选择器匹配但不是所有过滤器,这是什么意思?

html - 向左浮动无法正常工作

html - 什么是跨浏览器渲染?

javascript - jquery - 滑动页面计数

html - CSS Target 一个元素,该元素可能具有许多类之一

python-3.x - 我如何获得一张表格并将其放入 Excel 中而无需长代码