首页 文章

如何重用和覆盖Css样式?

提问于
浏览
0

好的,这是myResource.css

.gwtCellButton button {
  margin: 0;
  padding: 5px 7px;
  text-decoration: none;
  ....more styles here...

}

.gwtCellButton button:active {
  border: 1px inset #ccc;
}
.gwtCellButton button:hover {
  border-color: orange;
  color: orange;
}

现在我希望 .gwtCellButtonSmall.gwtCellButton 完全相同,只是它有 padding: 1px 2px;

当然,如果我这样做,那么我可以复制代码:

.gwtCellButtonSmall button {
  margin: 0;
  padding: 1px 2px;
  text-decoration: none;
  ....more styles here...

}

.gwtCellButtonSmall button:active {
  border: 1px inset #ccc;
}
.gwtCellButtonSmall button:hover {
  border-color: orange;
  color: orange;
}

3 回答

  • 3

    如果我正确理解你的问题,你想要有两个具有相似风格的元素,其中一个具有不同的 padding .

    是这样,您可以在两个元素之间共享样式:

    .gwtCellButton button, .gwtCellButtonSmall button{
        margin: 0;
        padding: 5px 7px;
        text-decoration: none;
        ...
    }
    

    然后使用!important覆盖特定元素的 padding

    .gwtCellButtonSmall button{
        padding: 1px 2px !important
    }
    

    或者你可以使用像Sass这样的东西 .

  • 1

    使用 !important . 如果有任何其他属性,则具有 !important 的属性将覆盖确切的属性 .

    所以你的情况,

    padding: 1px 2px!important;
    

    大量使用它们有时会导致一些问题 . 因此,不要忘记快速查看this summary .

  • 1

    您不需要复制任何代码,或者更糟糕的是,使用 !important .

    通过在每个HTML元素上指定两个类来使用修饰符类可以解决此问题:基本 gwtCellButton 类和修饰符类(在此示例中为 regularsmall ) .

    .gwtCellButton button {
      margin: 0;
      text-decoration: none;
    }
    
    .gwtCellButton.regular button {
      padding: 5px 7px;
    }
    
    .gwtCellButton.small button {
      padding: 1px 2px;
    }
    

    不必要地使用 !important 声明可能导致specificity issues下线 .

相关问题