在 CSS 中混合两种颜色作为背景

She*_*uti 5 html css background-image

我想将两种颜色叠加在另一种之上。我通过创建并合并两个 div 来做到这一点,其中一个位于顶部,不透明度为 60%。我想知道是否有一种更简单的方法,只需要一个具有两种颜色的 div,或者只需要一种混合了两种颜色的颜色。

我在这里发布我的代码,如果您发现任何不好的做法,请告诉我。我渴望提高自己的技能。

* {
  padding: 0;
  margin: 0;
  border: 0;
  box-sizing: border-box;
}


/* ~~~~~~~~~~SKY~~~~~~~~~~ */

#sky {
  position: relative;
  z-index: -100;
  width: 100vw;
  height: 100vh;
  background-image: linear-gradient( to top, midnightblue, black);
}


/* ~~~~~~~~~~MOON~~~~~~~~~~ */

.moon {
  position: absolute;
  top: 3%;
  right: 0%;
  width: 200px;
  height: 200px;
  border-radius: 50%;
}

#dark-moon {
  background-color: silver;
}

#light-moon {
  background-color: goldenrod;
  background-image: radial-gradient(dimgrey 20%, transparent 16%), radial-gradient(dimgrey 15%, transparent 16%);
  background-size: 60px 60px;
  background-position: 0 0, 30px 30px;
  opacity: 60%;
}


/* ~~~~~~~~~~SEA~~~~~~~~~~ */

#sea {
  position: absolute;
  bottom: 0%;
  width: 100vw;
  height: 25vh;
  background-color: #48B;
}
Run Code Online (Sandbox Code Playgroud)
<div id="sky">
  <div id="dark-moon" class="moon"></div>
  <div id="light-moon" class="moon"></div>
</div>

<div id="sea"></div>
Run Code Online (Sandbox Code Playgroud)

正如你所看到的,银色的月亮上方有一轮金色的月亮。只有一个月亮我怎样才能得到相同的结果?

Tem*_*fif 5

您可以使用伪元素和多个背景使用 0 个元素来完成此操作:

html {
  min-height: 100%;
  background: linear-gradient( to top, midnightblue, black);
}

html::before {
  content:"";   
  position: absolute;
  top: 3%;
  right: 0;
  width: 200px;
  height: 200px;
  border-radius: 50%;
  background: 
    linear-gradient(rgba(192,192,192,0.4) 0 0),
    radial-gradient(dimgrey 20%, transparent 16%), 
    radial-gradient(dimgrey 15%, transparent 16%) 30px 30px,
    goldenrod;
  background-size: 60px 60px;
}

html::after {
  content:"";
  position: absolute;
  bottom: 0;
  left:0;
  right:0;
  height: 25vh;
  background: #48B;
}
Run Code Online (Sandbox Code Playgroud)

另一个进一步优化代码的奇特想法:

html {
  min-height: 100%;
  background: 
   linear-gradient(#48B 0 0) bottom/100% 25vh no-repeat fixed,
   linear-gradient(black,midnightblue);
}

html::before {
  content:"";   
  position: absolute;
  top: 3%;
  right: 0;
  width: 200px;
  height: 200px;
  border-radius: 50%;
  background: 
    linear-gradient(#48B 0 0) bottom/100% 25vh no-repeat fixed,
    linear-gradient(rgba(192,192,192,0.4) 0 0),
    radial-gradient(dimgrey 20%, transparent 16%) 0    0   /60px 60px, 
    radial-gradient(dimgrey 15%, transparent 16%) 30px 30px/60px 60px,
    goldenrod;
}
Run Code Online (Sandbox Code Playgroud)