从CSS文件覆盖内联CSS而不添加!important

时间:2018-12-19 15:16:48

标签: html css css-selectors

我有一个角度成分,当他生成时,他正在以内联方式编写样式  html。

示例:

<my-component></my-component>

其html是:

<div id="my_component" class="class_1" style="width: 40px; height: 40px;"></div>

是否可以从外部CSS文件覆盖my_component的宽度/高度? 我尝试了很多选择器,但总是被内联样式覆盖...

!important 正在工作,但是我想知道是否有使用!important 以外的其他方式。

4 个答案:

答案 0 :(得分:3)

否。

不使用!important覆盖CSS规则的唯一方法是使用更具体的选择器。

没有选择器比style属性更具体。

答案 1 :(得分:1)

如果我们以不同的方式考虑要覆盖宽度/高度,那么可以使用min-width / min-height来实现:

XMLSerializer
#my_component {
  min-width:200px;
  min-height:200px;
  background:red;
}

为了更加准确,您可以添加max- *版本,以确保高度/宽度固定:

<div id="my_component" class="class_1" style="width: 40px; height: 40px;"></div>
#my_component {
  min-width:200px;
  min-height:200px;
  max-width:200px;
  max-height:200px;
  background:red;
}

答案 2 :(得分:0)

CSS特殊性在层次结构中起作用

  1. !important覆盖
  2. 内联样式
  3. ID的-HTML:id="blah",CSS:#blah
  4. 类-HTML:class="foo",CSS:.foo
  5. 元素和伪元素(:before:after)。

您可以详细了解here

但正如其他人所说,不。

答案 3 :(得分:0)

a selector containing 256 would override an id曾经存在一个错误。计数器可能有一些上限,超过该上限将导致覆盖下一个值(256个id的选择器将覆盖内联样式)。

我认为256个类的错误是固定的,我不知道是否通过增加必要的类数或放置一些阻止它再次发生的方法来完成。

从纯粹的学术角度来看,可能无需使用!important就可以覆盖内联样式,但与规范/ a的一部分不同,这更多是一个漏洞利用好主意。