【问题标题】:Border color based on background基于背景的边框颜色
【发布时间】:2014-05-24 18:34:07
【问题描述】:

我经常在我的 SASS 样式中使用 darkenlighten。我目前正在编写一个有边框的类,但将依赖于另一个类的背景颜色。我想要做的是将边框颜色设置为元素背景颜色的darken

类似这样的:

.blue { background: #00f; }
.red  { background: #f00; }

.border { border: 2px solid darken(background, 20); }

那么标记将是:

<div id="colored-box" class="blue border">
  <p>
    I have a dark blue border!
  </p>
</div>

<div id="colored-box" class="red border">
  <p>
    I have a dark red border!
  </p>
</div>

当然,如果按照我在这里写的那样工作,我就不会在 SO 上发布这个问题 :)

所以问题是:我能否将border 颜色基于background 属性动态,如果可以,如何?

【问题讨论】:

    标签: html css sass background-color


    【解决方案1】:

    有两种方法可以加深边框颜色(目前 - 没有 sass)。

    1. 作为@user3341679's answer,使用rgba()
    2. 正在使用过滤器 birghtness()opacity()
    .box {
        border: 5px solid rgba(100, 100, 100, 1);
        filter: brightness(.72) opacity(.7);
    }
    

    完整示例:https://jsfiddle.net/3qwo85js/2/

    图片预览

    使用 2 种 css 方式使边框变暗。

    放大深边框颜色。

    【讨论】:

      【解决方案2】:

      如前所述,我会这样做,但要安全重置background-clip;

      .border { border: 2px solid rgba(0,0,0,0.2);/* set here opacity to darken 
      to lighten , use rgba(255,255,255,0.X) , any other color can be used too*/
      background-clip:border-box; /* make sure bg is layed under border */
      }
      

      DEMO


      将此视为使用 rgba() 颜色的提醒,如 hsla() 颜色

      【讨论】:

      • 使用rgba颜色可以很容易地变亮,变暗或添加颜色:codepen.io/gc-nomade/pen/wouBe它是基本的颜色层喷涂任何东西,实际上只是一个提醒:)
      【解决方案3】:

      我会使用这样的 mixin:

      .darkenBorder(@color) {
          &.border { 
              background: darken(@color, 20);
          }
      }
      

      这样,您可以轻松地为任何颜色添加深色边框样式:

      .blue { background: #00f; .darkenBorder(#00f); }
      .red  { background: #f00; .darkenBorder(#f00); }
      

      使用相同的想法甚至更简单(或至少更干燥):

      .colorStyles(@color) {
          background: @color;
          &.border { 
              background: darken(@color, 20);
          }
      }
      .blue { .colorStyles(#00f); }
      .red  { .colorStyles(#f00); }
      


      输出:
      .blue {
        background: #00f;
      }
      .blue.border {
        background: #000099;
      }
      .red {
        background: #f00;
      }
      .red.border {
        background: #990000;
      }
      

      【讨论】:

        【解决方案4】:

        虽然不是 SASS 解决方案,但您可以只使用 rgba。

        .border {
          border: 2px solid rgba(0,0,0, 0.25);
        }
        

        jsfiddle 为例。

        【讨论】:

        • 这是最自然的方式。 +1
        • 虽然我确实喜欢利用 SASS mixins,但这是迄今为止最直接的答案,并且比其他答案更容易与我现有的样式联系起来。谢谢!
        猜你喜欢
        • 2015-07-05
        • 1970-01-01
        • 2011-09-12
        • 2015-03-07
        • 2017-09-19
        • 1970-01-01
        • 2015-04-21
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多