CSS样式的继承与覆盖

样式的继承

定义:父元素设置了某属性,子元素也会有该属性

下面是会被继承的CSS样式属性:

azimuth, border-collapse, border-spacing,
caption-side, color, cursor, direction, elevation,
empty-cells, font-family, font-size, font-style,
font-variant, font-weight, font, letter-spacing,
line-height, list-style-image, list-style-position,
list-style-type, list-style, orphans, pitch-range,
pitch, quotes, richness, speak-header, speaknumeral,
speak-punctuation, speak, speechrate,
stress, text-align, text-indent, texttransform,
visibility, voice-family, volume, whitespace,
widows, word-spacing

文本相关属性:

font-family, font-size, font-style,
font-variant, font-weight, font, letter-spacing,
line-height, text-align, text-indent, texttransform,word-spacing

列表相关属性:

list-style-image, list-style-position,
list-style-type, list-style

样式的覆盖

规则:

  • 根据引入方式确定优先级
    优先级由高到低依次为:“内联属性”——>“写在 style标签里”——>“外部链接”
  • 后写的覆盖先写的(同一级别)
    即就是在文件上代码行号更靠下的优先级更高
  • 加有“!important”的样式,优先级最高
    即无论哪一种情况,只要在样式上加了important,那么该样式的优先级最高。加了important的代码如下:
p {
     color: white !important;
}
  • 选择器优先级
    在选择器不同的情况下,给每种选择器制定一个权值,计算命中一个元素的所有选择器的总权值,值高者获胜
  • 元素选择器: 1
  • 类选择起器: 10
  • ID选择器: 100
  • 内联选择器: 1000

样式继承与覆盖示例

  • 样式继承不是一个默认行为,实际上而是看某一个属性的默认值是否是inherit。 所谓的浏览器默认样式。a标签的color浏览器默认样式不是inherit。代码如下所示:
.abstract{
    color:grey;
}
.abstract a{
    color:inherit;
    text-decoration:none;
    border:thin black solid;
}
.different {
    color: red ;
}
.different a{
    text-decoration: none ;
    border:thin black solid;
}

执行效果如下图:


demo1.png
详细代码[点这里](https://github.com/tw-lab-roadmap-1/YangHuili-task2-homework2/tree/master/demo1)
  • 前面讲到外部文件引用css的优先级比style标签里的低。 但是id选择器的优先级是比元素选择器要高的。所以当元素选择器和id选择器都命中同样的元素的时候, id选择器的样式会覆盖元素选择器的样式。
    代码如下:
  h1{
    color:red;
 }
  #change{
    color:blue;
}

执行效果如下:

demo2.png

详细代码 点这里

  • 我们知道内联样式的优先级是最高的,那么当元素已经被内联样式设置的时候。我们通过 !important 来覆盖。代码如下:

     

HelloWord,你看到的是已经经历过三次变换的文字。

h1{
    color: red;
 }
#change{
    color:black !important
}

执行效果如下:

demo3.png

详细代码 点这里

  • 若给一种元素设置了普适的效果,如何通过更精确的选择器将其覆盖掉,代码如下:
a{
    color:black;
}
a.hehe{
    color:white;
    background:grey;
}

详细代码点这里

  • 当一个元素有两个class的时候,到底哪个class会影响 元素呢, 代码如下:
a.hehe1{
    color:black;
}
a.hehe2{
    color:white;
    background:grey;
}

文件上代码行号更靠下的优先级更高,即后写的覆盖先写的。
详细代码点这里

  • 让span继承abstract的border属性。代码如下:
.abstract{
    color:white;
    background:grey;
    border:medium black solid;
}
span{
    border:inherit
}

如上所示,将span 的 border 属性设为“inherit”,span 就会继承父元素的样式。
详细代码点这里

你可能感兴趣的:(CSS样式的继承与覆盖)