【问题标题】:CSS: Colored div with transparent box [duplicate]CSS:带透明框的彩色 div [重复]
【发布时间】:2016-08-28 12:48:41
【问题描述】:

有没有办法让一个 div 的背景颜色占据 100% 的宽度,并在其中有一个显示原始背景的透明框?

【问题讨论】:

标签: html css


【解决方案1】:

解决方案 1:剪辑路径

剪辑路径非常有用,因为它可以保持代码简洁明了。但是,它在浏览器中还没有得到很好的支持,因此只能在测试环境中使用。

html {
  background: url("http://butlers-web.co.uk/Content/Images/BWLOGO.png") 100% 100%;
}
div {
  height: 300px;
  width: 100%;
  background: tomato;
  position: relative;
  -webkit-clip-path: polygon(0% 0%, 0% 100%, 100% 100%, 100% 0, 50% 0, 50% 20%, 80% 20%, 80% 80%, 20% 80%, 20% 20%, 50% 20%, 50% 0);
}
<div>

</div>

解决方案 2:盒子阴影技巧

盒子阴影技巧使用伪元素和overflow:hidden; 来创建元素的盒子阴影/着色。

html {
  background: url("http://butlers-web.co.uk/Content/Images/BWLOGO.png") 100% 100%;
}
div {
  height: 300px;
  width: 100%;
overflow:hidden;
  position: relative;
}
div:before{
  content:"";
  position:absolute;
  top:20%;width:60%;height:60%;left:20%;
  box-shadow:0 0 0 999px tomato;
  }
&lt;div&gt;&lt;/div&gt;

解决方案 3:渐变

您可以使用多个渐变背景,但这可能适合也可能不适合,因为渐变并不总是能很好地呈现:

html {
   background: url("http://butlers-web.co.uk/Content/Images/BWLOGO.png") 100% 100%;
 }
 div {
   position: relative;
   height: 300px;
   width: 100%;
   background: linear-gradient(tomato, tomato), linear-gradient(tomato, tomato), linear-gradient(tomato, tomato), linear-gradient(tomato, tomato);
   background-size: 100% 20%, 20% 100%, 100% 20%, 20% 100%;
   background-position: left bottom, right bottom, left top, left top;
   background-repeat: no-repeat;
 }
&lt;div&gt;&lt;/div&gt;

解决方案 4:边框

虽然这可能适合您,也可能不适合您,但仍有可能会有所帮助,因此无论如何都会在此处发布:

html {
   background: url("http://butlers-web.co.uk/Content/Images/BWLOGO.png") 100% 100%;
 }
 div {
   position: relative;
   height: 300px;
   width: 100%;
   box-sizing: border-box;
   border-left: 20vw solid tomato;
   border-right: 20vw solid tomato;
   border-top: 50px solid tomato;
   border-bottom: 50px solid tomato;
 }
&lt;div&gt;&lt;/div&gt;

解决方案 5:背景附件

我最近遇到了background-attachment 属性,所以我仍然在处理它。但是,如果您希望背景出现在后面,您可以根据需要更改以下 sn-p:

body {
  background: url('http://butlers-web.co.uk/Content/Images/BWLOGO.png');
  background-attachment: fixed;
}
.wrapper {
  width: 100%;
  height: 300px;
  background: tomato;
  position: relative;
}
.inner {
  width: 80%;
  height: 80%;
  background: url('http://butlers-web.co.uk/Content/Images/BWLOGO.png');
  background-attachment: fixed;
  position: absolute;
  top: 10%;
  left: 10%;
  box-sizing:border-box;
  border:2px solid black;
}
<div class="wrapper">
  <div class="inner"></div>
</div>

【讨论】:

【解决方案2】:

您将需要两个 div。父级,红色背景,然后是内部 div。

给内部 div 边距:10px auto;作为一个开始。

【讨论】:

  • OP 没有使用两个 div,如@Nenad 在 cmets 中提供的链接所示。
  • 子 div 的背景将被重新调整为更小。
  • 从未想过使用 :after。它有效,但可能不是孩子需要持有 CSS 无法注入的东西的最佳解决方案。
猜你喜欢
  • 2013-10-03
  • 1970-01-01
  • 2015-06-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多