开发者

CSS problem - an element only works if its has no parent (using jquery)

开发者 https://www.devze.com 2023-01-27 17:50 出处:网络
i have this code: CSS: .taglist { float:left; margin-left:30px; } .taglist ul { overflow:auto; list-style-type:none;

i have this code:

CSS:

.taglist 
{
    float:left;
    margin-left:30px;
}
.taglist ul 
{
    overflow:auto;
    list-style-type:none;
    border:1px solid #999;
    background:#ccc;
    padding:20px;
    min-height:150px;
    max-height:150px;
    width:100px;
}

.taglist li
{
    display:block;
    border:1px solid #999;
    background:#fff;
    width:80px;
    padding:5px 10px;
    margin-bottom:5px;
}
.tag_selected {
    background:#ffc;
}
开发者_开发百科

HTML:

<div class="taglist">
    <ul id="list1">
        <li id="1">1</li>
    </ul>
</div>

Now I'm using jQuery for this one.. so when an item on the list is selected, it should change its class to tag_selected.

Problem is, it only works if i remove the ".taglist " before the ul and li css, and i don't want to do it because i want the style only to be on the "taglist" div..

i'v tried every combination like ".taglist tag_selected", ".taglist ul li tg_selected", etc. but nothing works !!

what can I do?

btw, trying this line:

<li class="tag_selected" id="1">1</li>

gave the same result, no change what so ever..

Thanks in advance!


Your problem seems to be CSS selector specificity.

The rules .taglist ul and .taglist li are more specific than .tag_selected and therefore your class is assigned but the background is overridden by .taglist li.

This should work

.taglist li.tag_selected {
    background:#ffc;
}

The specificity order (weakest to strongest) tag, class, ID. The easiest way to remember to calculated it is treat the sum of each as a digit, with tag as the 1s, class as the 10s, and ID as the 100s.

  • li - 1
  • .taglist - 10
  • .taglist li - 11
  • li#myId - 101
  • div.taglist li.tag_selected - 22

See http://htmldog.com/guides/cssadvanced/specificity/ for help or Google "css specificity".

0

精彩评论

暂无评论...
验证码 换一张
取 消