【问题标题】:How to encapsulate CSS properties to prevent repeating myself如何封装CSS属性防止重复自己
【发布时间】:2017-12-11 19:27:31
【问题描述】:

我正在向一个元素添加两个具有相同值的 CSS 属性:

var hex = window.lineColors[a.options.labels.length - 1];

$('.container#buttonContainer').append('<button type="button" class="btn btn-primary" style="background-color:' + hex + '; border-color: ' + hex + '">' + date.format("DD/MM/YYYY") + '</button>');

如您所见,background-colorborder-color 共享相同的值 hex,我正在尝试探索消除这种重复的最佳方法。

由于hex 包含多个预选值之一,一种可能性是为每个值设置一个 CSS 类,例如:

button_003C69
{
   background-color: #003C69;
   border-color: #003C69;
}

我可以使用预处理器自动生成这些。

我还希望我能以某种方式将十六进制传递给 CSS 类以供它使用,但只有预处理器允许这样做,因此在运行时不可用。

我只知道我在这里错过了一个技巧,你们如何最好地处理这种情况?

【问题讨论】:

  • CSS 变量? (当然,还没有 IE 支持。)

标签: html css sass


【解决方案1】:

一种选择就是声明一个标准的透明边框。

然后背景颜色显示通过边框。

button {
  /* demo properties */
  width:200px;
  height:75px;
  display: block;
  margin:10px auto;
  border-width:5px;
  border-style:solid;
  /* transparent border */
  border-color:transparent
}

.A {
  background: pink;
}

.B {
  background: lightblue;
}
<button>No Class</button>
<button class="A">Button A</button>
<button class="B">Button B</button>

【讨论】:

  • 开箱即用,我喜欢!
猜你喜欢
  • 1970-01-01
  • 2015-01-21
  • 1970-01-01
  • 2013-01-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-30
  • 1970-01-01
相关资源
最近更新 更多