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

执行效果如下图:
在这里插入图片描述

  • 前面讲到外部文件引用css的优先级比style标签里的低。但是id选择器的优先级是比元素选择器要高的。所以当元素选择器和id选择器都命中同样的元素的时候, id选择器的样式会覆盖元素选择器的样式。 代码如下:
h1{
    color:red;
 }

#change{
    color:blue;
}

执行效果如下:
demo2.png

  • 我们知道内联样式的优先级是最高的,那么当元素已经被内联样式设置的时候。我们通过 !important来覆盖。代码如下:
<body>
     <h1 id="change" style="color: grey">
          HelloWord,你看到的是已经经历过三次变换的文字。
    </h1>
</body>
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继承abstractborder属性。代码如下:
.abstract{
    color:white;
    background:grey;
    border:medium black solid;
}
span{
    border:inherit
}

如上所示,将spanborder 属性设为“inherit”,span 就会继承父元素的样式。

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值