首页 > 解决方案 > 不使用 !important 覆盖来自 CSS 文件的内联 CSS

问题描述

我有一个角度组件,它style在生成的 HTML 中生成内联属性。

例子 :

<my-component></my-component>

该组件的 HTML 是:

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

有没有办法覆盖my_component外部 CSS 文件的宽度/高度?我尝试了很多选择器,我总是被内联样式覆盖......

!important 有效,但我想知道是否有其他方法可以使用 !important。

标签: htmlcsscss-selectors

解决方案


如果考虑到您想要覆盖宽度/高度,我们以不同的方式考虑这一点,那么是的,您可以使用 min-width/min-height 来做到这一点:

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

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

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


推荐阅读