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

标签 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;
}
<div id="sky">
  <div id="dark-moon" class="moon"></div>
  <div id="light-moon" class="moon"></div>
</div>

<div id="sea"></div>

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

最佳答案

您可以使用伪元素和多个背景对 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;
}

另一个优化代码的奇思妙想:

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;
}

关于html - 在 CSS 中为背景混合两种颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65219464/

相关文章:

php - 远程缓存自动完成问题

HTML:由于包装器,页面背景图片链接不起作用

php - 在 html 中使用 "php if"更改 <td> 颜色背景

html - 如何为具有背景图像的 div 指定百分比高度?

javascript - 使用 background-size : cover with Javascript? 时是否可以测量生成的背景图像

javascript - Chart.js 随机 RGB 背景颜色生成器不工作

javascript - 我怎样才能让用户只输入数字(带/不带小数点)。或数字与 'K'/'B'

javascript - 服务中的 $http 返回 Angularjs 服务中 $$state 的值

javascript - 我应该如何使用图像来触发 Javascript?

html - IE 10、11 背景大小问题