首页 > 解决方案 > 如何覆盖内联 CSS 背景色不透明度,而不是颜色?

问题描述

该网页有一个块列表,如下所示。每个块的背景颜色以 0.5 不透明度内联完成。0.5 的不透明度是问题所在。我需要它完全不透明。我正在使用 Stylish Chrome 扩展,我需要使用外部 CSS 来完成。

<a class="pizza" style="background-color:rgba(255, 255, 0,0.5);>this is yellow</a>
<a class="pizza" style="background-color:rgba(255, 0, 0,0.5);>this is red</a>

我知道如何更改不透明度的唯一方法还包括将每个块的颜色更改为相同。但是列表中的每个块都有自己的颜色,并且需要保持自己的颜色。如何在不更改颜色的情况下更改所有块的不透明度?

我想要这样的东西:

a.pizza {
  background-color: rgba(, , , 1);
}

或者像这样:

a.pizza {
  background-color-opacity: completely opaque !important;
}

标签: htmlcssopacity

解决方案


我想出了一些技巧。它不会让你回到 100% 的不透明度,但非常接近。

问题是,如果没有 JavaScript,就无法找出颜色是什么并据此采取行动。因此,您可以改为使用 CSSinherit作为子元素的背景颜色,并将它们分层以增加主元素的整体感知不透明度。

因此,通过添加两个继承背景颜色的伪元素并将它们定位在主元素后面,您可以获得非常接近 100% 的不透明度:

/* For the demo */
.pizza {  
  display: inline-block;
  vertical-align: top;      
  width: 120px;
  height: 120px;
}

/* Add relative positioning so we can position the absolute children correctly */
.pizza.new {
  position: relative;
}

/* Add two pseudo elements behind that inherit the background color */
.pizza.new::before,
.pizza.new::after {
  /* Sizing and positioning */
  display: block;
  position: absolute;
  content: '';
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  /* Take the background color of the parent */
  background: inherit;
  /* Make sure they're not obscuring the content */
  z-index: -1;
}
<a class="pizza" style="background-color: rgba(255, 255, 0, 0.5);">
  This is yellow (before)
</a>

<a class="pizza" style="background-color: rgba(255, 0, 0, 0.5);">
  This is red (before)
</a>

<a class="pizza new" style="background-color: rgba(255, 255, 0, 0.5);">
  This is yellow (after)
</a>

<a class="pizza new" style="background-color: rgba(255, 0, 0, 0.5);">
  This is red (after)
</a>


推荐阅读