簡體   English   中英

CSS:樣式化ID無效

[英]CSS: Styling IDs not having any effect

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

為什么樣式不起作用?

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

您可以以數字開頭的ID選擇器(詳細說明Xec的答案),但是在CSS中,這不是一個好習慣,它需要轉義或以字母開頭。 我建議您在HTML中使用id="img2"類的名稱進行更改。 並在CSS中使用#img2

以數字開頭的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/

為了簡化選擇器,我建議您以字母字符(az)開頭的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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM