如何重用和覆盖Css样式?

时间:2014-02-10 00:11:37

标签: html css

好的,这是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 个答案:

答案 0 :(得分:3)

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

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

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

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

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

或者您可以使用类似Sass的内容。

答案 1 :(得分:1)

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

所以你的情况,

 padding: 1px 2px!important;

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

答案 2 :(得分: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失效。