【问题标题】:CSS: Styling IDs not having any effectCSS:样式ID没有任何效果
【发布时间】:2013-06-07 11:15:50
【问题描述】:
<div id="mydiv">
<img width="190" height="190" src="http://distilleryimage0.s3.amazonaws.com/9fe1cfd2cd4311e28e5722000a9f195f_6.jpg" id="1">
<img width="190" height="190" src="http://distilleryimage0.s3.amazonaws.com/9fe1cfd2cd4311e28e5722000a9f195f_6.jpg" id="2">
<img width="190" height="190" src="http://distilleryimage0.s3.amazonaws.com/9fe1cfd2cd4311e28e5722000a9f195f_6.jpg" id="3">
<img width="190" height="190" src="http://distilleryimage0.s3.amazonaws.com/9fe1cfd2cd4311e28e5722000a9f195f_6.jpg" id="4">
<img width="190" height="190" src="http://distilleryimage0.s3.amazonaws.com/9fe1cfd2cd4311e28e5722000a9f195f_6.jpg" id="5">
<img width="190" height="190" src="http://distilleryimage0.s3.amazonaws.com/9fe1cfd2cd4311e28e5722000a9f195f_6.jpg" id="6">
</div>

<style>
div#mydiv img#1 {width:30px}
div#mydiv img#2 {width:60px}
</style>

为什么样式不起作用?

Js 小提琴:http://jsfiddle.net/FqrDR/1/

【问题讨论】:

    标签: css html stylesheet styling


    【解决方案1】:

    您可以使用数字开始 ID 选择器(详细说明请查看 Xec 的答案),但在 CSS 中它不是一个好的做法,它需要转义或以字母开头。我建议您在 HTML 中将其更改为 id="img2" 之类的名称。并在 css 中使用 #img2

    【讨论】:

      【解决方案2】:

      以数字开头的 ID 在 HTML5 中完全有效,但不幸的是,如果不转义第一个字符,或者使用属性选择器,您无法在 css 中使用哈希表示法选择它;

      /* unicode 0031 == "1" */
      div#mydiv img#\0031 {width:30px} 
      
      /* works, but has less specificity than hash notation */
      div#mydiv img[id="2"] {width:60px}
      

      http://jsfiddle.net/FqrDR/3/

      为了使您的选择器更简单,我建议您以字母字符 (a-z) 开头的 ID 命名。

      来源

      1. 博客文章:http://mathiasbynens.be/notes/html5-id-class
      2. 规格: http://www.whatwg.org/specs/web-apps/current-work/multipage/elements.html#the-id-attribute
      3. W3C 常见问题解答:http://www.w3.org/International/questions/qa-escapes#cssescapes

      【讨论】:

        猜你喜欢
        • 2015-01-05
        • 1970-01-01
        • 1970-01-01
        • 2018-10-17
        • 2016-04-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多