• css样式被覆盖解决方案


    刚才写zenktodo的时候,通过动态添加class的方式修改一个div的样式,总是不起作用。

    Css代码  收藏代码
    1. #navigator {  
    2.     height: 100%;  
    3.      200;  
    4.     position: absolute;  
    5.     left: 0;  
    6.     border: solid 2 #EEE;  
    7. }  
    8.   
    9. .current_block {  
    10.     border: solid 2 #AE0;  
    11. }  

    查找一些教材中(w3schools等),只说css的顺序是“元素上的style” > “文件头上的style元素” >“外部样式文件”,但对于样式文件中的多个相同样式的优先级怎样排列,没有详细说明。经过测试和继续搜索,得知优先级如下排列:

    1. 样式表的元素选择器选择越精确,则其中的样式优先级越高:

    id选择器指定的样式 > 类选择器指定的样式 > 元素类型选择器指定的样式

    所以上例中,#navigator的样式优先级大于.current_block的优先级,即使.current_block是最新添加的,也不起作用。

    2. 对于相同类型选择器指定的样式,在样式表文件中,越靠后的优先级越高

    注意,这里是样式表文件中越靠后的优先级越高,而不是在元素class出现的顺序。比如.class2 在样式表中出现在.class1之后:

    Css代码  收藏代码
    1. .class1 {  
    2.     color: black;  
    3. }  
    4.   
    5. .class2 {  
    6.     color: red;  
    7. }  

    而某个元素指定class时采用 class="class2 class1"这种方式指定,此时虽然class1在元素中指定时排在class2的后面,但因为在样式表文件中class1处于class2前面,此时仍然是class2的优先级更高,color的属性为red,而非black。

    3. 如果要让某个样式的优先级变高,可以使用!important来指定:

    Css代码  收藏代码
    1. .class1 {  
    2.     color: black !important;  
    3. }  
    4.   
    5. .class2 {  
    6.     color: red;  
    7. }  

     此时class将使用black,而非red。

    对于一开始遇到的问题,有两种解决方案:

    1. 将border从#navigator中拿出来,放到一个class .block中,而.block放到.current_block之前:

    Css代码  收藏代码
    1. #navigator {  
    2.     height: 100%;  
    3.      200;  
    4.     position: absolute;  
    5.     left: 0;  
    6. }  
    7.   
    8. .block {  
    9.     border: solid 2 #EEE;  
    10. }  
    11.   
    12. .current_block {  
    13.     border: solid 2 #AE0;  
    14. }  

     需要默认为#navigator元素指定class="block"

    2. 使用!important:

    Css代码  收藏代码
    1. #navigator {  
    2.     height: 100%;  
    3.      200;  
    4.     position: absolute;  
    5.     left: 0;  
    6.     border: solid 2 #EEE;  
    7. }  
    8.   
    9. .current_block {  
    10.     border: solid 2 #AE0 !important;  
    11. }  

     此时无需作任何其他改动即可生效。可见第二种方案更简单一些。

  • 相关阅读:
    howtoautomateyouriphoneappbuildswithhudson
    buildingiphoneappswithhudsonpart2
    Linux常用命令全集
    介绍
    Linux文件查找命令find,xargs详述
    Tomcat for Mac OS
    Jenkins在Mac平台安裝
    Linux下的shell与make
    buildingiosappsforovertheairadhocdistribution
    linux下u盘的使用
  • 原文地址:https://www.cnblogs.com/lvfeilong/p/sdfdsf435435.html
Copyright © 2020-2023  润新知