【问题标题】:How to Change the background color of div element to match with body background color? [duplicate]如何更改 div 元素的背景颜色以匹配正文背景颜色? [复制]
【发布时间】:2019-10-31 18:20:54
【问题描述】:

在线性渐变背景中,我创建了一个圆圈,并在其中创建了一个小正方形。圆形是dodgerblue,正方形应该是body的linear-gradient,但问题是div元素的linear-gradient位置与body背景不匹配。

我试过background:inherit用div元素,但是渐变和body不匹配。

body {
  background: linear-gradient(45deg, yellow, green);
  background-size: 400% 400%;
}

.circle {
  height: 150px;
  width: 150px;
  border-radius: 50%;
  position: relative;
  margin: auto;
  background: dodgerblue;
}

.square {
  height: 50px;
  width: 50px;
  transform: translate(250px, -100px);
  background: inherit;
}
<body>
  <div class="circle"></div>
  <div class="square"></div>
</body>

【问题讨论】:

  • 您可以使用background-attachment: fixed;,但我认为您需要使用lefttop 属性来定位元素而不是转换。
  • 不行,body和div背景还是有区别的
  • 显然,如果您将background-attachment: fixed; 添加到body,它会起作用。但是您正在失去对渐变外观的一些控制(它在 400% 的比例下变得不那么突出)。 (编辑:那个,加上绝对定位而不是转换。)(编辑2:jsfiddle.net
  • 我想要的是正方形像透明但不是圆形背景它应该有身体背景。

标签: html css


【解决方案1】:

继承body背景图片的问题是body和circle元素的大小差异。所以你真正想要实现的是一种打孔式的布局元素,它暴露了身体背景的一部分。 这是一种更改 HTML 的方法,其中圆是圆元素的伪元素。伪元素实际上会用box-shadow 为圆圈着色,并使透明正方形可见。

body {
  background: linear-gradient(45deg, yellow, green);
  background-size: 400% 400%;
}

.circle-with-square {
  height: 150px;
  width: 150px;
  border-radius: 50%;
  margin: auto;
  position: fixed;
  align-items: center;
  overflow: hidden;
  display: flex;
  flex-flow: column nowrap;
  justify-content: center;
}

.circle-with-square::after
{
  content: "";
  height: 50px;
  width: 50px;
  display: block;
  box-shadow: 0 0 0 150px dodgerblue;
}
<body>
  <div class="circle-with-square"></div>
</body>

【讨论】:

  • 多么好的解决方案!您应该提到正方形也可以使用 box-shadow 属性的 x/y 移动
  • @Apolo 很高兴它有帮助。您还可以使用任何类型的位置变换来移动正方形本身。祝你好运!
  • 可以用三角形吗
  • 这需要一些努力,但应该可以。最简单的方法是添加一个三角形的 svg 作为实际元素,这将投射彩色阴影。
猜你喜欢
  • 2014-10-14
  • 1970-01-01
  • 1970-01-01
  • 2011-11-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多