【问题标题】:In CSS, can "#footer #caption" coexist with "#content #caption"?在 CSS 中,“#footer #caption”可以与“#content #caption”共存吗?
【发布时间】:2011-03-03 16:54:44
【问题描述】:

我打算像这样“嵌套”CSS ids

#content #caption { color: teal }
  ...

#footer #caption { margin: 2em 1em }

因为这是 SASS(一个 CSS 生成器)可以嵌套的方式...但是在一个 HTML 文档中,我们不能有两个同名的 ids,不是这样,所以上面的嵌套不会工作或不能很好地工作。 (尤其是如果需要 document.getElementById() 或 $('#caption') 或 $('caption') 来选择元素)。

我们可以使用

#content #content_caption { color: teal }
  ...

#footer #footer_caption { margin: 2em 1em }

但是为什么还要多一层嵌套呢?为什么不只是

#content_caption { color: teal }
  ...

#footer_caption { margin: 2em 1em }

?

【问题讨论】:

    标签: css stylesheet styles sass nested


    【解决方案1】:

    “标题”一词表明它不是唯一标识符。如果是这样,我会将标题声明为一个类。以下是完全合法有效的:

    #content .caption { color: teal }
    #footer .caption { margin: 2em 1em }
    

    【讨论】:

    • 看起来不错,虽然大量使用类,但它不是所谓的“CSS classitis”吗?
    • 当然,您永远不必过多地使用它。如果看起来合乎逻辑,使用标题可能会更好。然后你可以在 h1 或 h2 上进行匹配。
    【解决方案2】:

    没有理由。 id 是一个非常重的选择器,它应该足以改变样式规则。 if not append the #content before or change the selectors of the rules that arewinning.

    【讨论】:

    • “重”是什么意思?以什么方式?
    • 例如:#test{color: red} div{color: green}
      asdf
      现在 asdf 是红色的,因为红色规则有一个更强大的选择器.如果我没记错的话,ids 得到 100 分类 10 和元素 1。
    • 这个“点”的解释对我来说从来没有意义,因为 11 个类仍然低于一个 id。您必须将它们视为单独的事物,不能将它们加在一起。 “点”的一般概念仅用于说明。
    【解决方案3】:

    如果单个页面上没有两个id="caption"的元素,那就完全OK了。 但是,我从命名(内容和页脚)猜想,id =“caption”的不止一个,这很糟糕。您应该记住,id 必须是唯一的!请改用“class”,例如

    #content .caption { }
    #footer .caption { }
    

    【讨论】:

      【解决方案4】:

      首先,像“caption”这样的东西听起来确实更像是一个类:

      您说:这是 **the** 页脚(特定 id),但 这是 **a** 标题(一般类)。

      这是在 Sass 中嵌套选择器的另一种方式:

      .caption
        margin: 2em 1em
        font-weight: bold
        #footer &
          background: teal
        #content &
          background: red
      

      (“&”引用它所包含的任何内容。)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-10-19
        • 2019-01-31
        • 2021-11-07
        • 1970-01-01
        • 1970-01-01
        • 2021-06-01
        • 1970-01-01
        • 2010-11-05
        相关资源
        最近更新 更多