【问题标题】:How to avoid CSS inheritance to keep linear gradient background color intact?如何避免 CSS 继承以保持线性渐变背景颜色不变?
【发布时间】:2021-03-11 18:37:42
【问题描述】:

如何避免 CSS 继承以保持线性渐变背景颜色不变? 基本上我想避免将“box”(类名)div 中的红色背景色赋予.box-child div。我希望.box-child 保持在.main-box div 上设置的初始背景颜色。

通常我只会将背景颜色设置回原来的颜色,但它是线性渐变背景,如果我将其设置回一个小区域,它看起来就不像它应该的样子。我想保持原样。

.main-box {
  color: white;
  height: 500px;
  background: linear-gradient( 180deg, rgba(2, 0, 36, 1) 0%, rgba(84, 9, 121, 1) 35%, rgba(0, 212, 255, 1) 100%);
}

.box {
  height: 300px;
  background: red;
}

.box-child {
  height: 150px;
  inherits: none;
}
<div class="main-box">
  MAIN BOX
  <div class="box">
    BOX
    <div class="box-child">
      BOX CHILD
    </div>
  </div>
</div>

【问题讨论】:

  • 我不明白你的目标是什么,哪里出了问题。你能描述一下你的成就吗?
  • 我需要 .box-child 与 .main-box 具有相同的背景。如果我手动将 .box-child 背景设置回原来的样子,它将重新开始渐变背景 - 我需要它来保持 .box-child 从 .main-box 继承背景而不是 .box。
  • 我需要向外使用border-radius,为此我需要使用2个div——我认为这是一个更简单的示例。如果我不使用线性渐变背景,那么我会在 .box-child 上手动设置背景颜色,这样就可以解决了。
  • 你可能把一个简单的任务复杂化了,检查一下:stackoverflow.com/q/51496204/8620333
  • 我需要类似stackoverflow.com/questions/65071009/…的东西,实现起来可没那么简单。

标签: html css background-color linear-gradients


【解决方案1】:

据我了解,目的是为 box-child 元素提供与 main 相同的背景 - 即为它提供它所在的 main 的背景。

如果我们给 box-child 一个伪元素,它位于它的后面,但与 main 具有相同的尺寸、位置和背景,然后向 box-child 添加一个剪辑路径以删除伪元素的那些位,就可以做到这一点不在其中的元素。

/* give the box-child before pseudo element the same dimensions and same background as main */
.main-box, .box-child::before {
  height: 500px;
  background: linear-gradient(
    180deg,
    rgba(2, 0, 36, 1) 0%,
    rgba(84, 9, 121, 1) 35%,
    rgba(0, 212, 255, 1) 100%
  );
}

.main-box {
  color: white;
  position: relative;
}

.box {
  height: 300px;
  background: red;
}

.box-child {
  height: 150px;
  clip-path: inset(0);
}

.box-child::before{
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  z-index: -1;
}
  <div class="main-box">
    MAIN BOX
    <div class="box">
      BOX
      <div class="box-child">
        BOX CHILD
      </div>
    </div>
  </div>

【讨论】:

    猜你喜欢
    • 2021-09-11
    • 1970-01-01
    • 2021-07-20
    • 2014-08-12
    • 1970-01-01
    • 1970-01-01
    • 2019-02-01
    • 1970-01-01
    • 2022-12-21
    相关资源
    最近更新 更多