如何用不同的颜色左右扩展包裹的元素背景?

How to extend a wrapped element background both left and right with different color?

我正在尝试使用 CSS::before:after 伪元素将环绕元素扩展到整个浏览器宽度。

这是我的HTML:

 <section class="top-banner">
  <div class="flash-banner">  
    <object width="1003" height="121">
      <param name="movie" value="img/banner_header.swf">
      <embed src="img/banner_header.swf" width="1003" height="121">
      </embed>
    </object>
  </div>
</section>

.flash-banner DIV 已居中页面。所以我需要用两种颜色填充这个DIV的左右空格。

检查此图像以清楚地理解:

我就是这样试的。但我还是想不通。

.top-banner {
    text-align: center;
}

.flash-banner {
    background: #2D3447;
    height: 121px;
    position: relative; 
  margin: 0 -30px;
  padding: 0.25rem 30px;
  background: #333;
}

.flash-banner:before, 
.flash-banner:after {
  content: "";
  position: absolute;
  top: 0;
  bottom: 0;
  width: 9600px;
  right: 100%;
  background: green;
}

.flash-banner:after { 
  width: 150%;
  left: 100%;
  background: green;
}

希望有人能帮助我。谢谢你。

我将你的代码放在 jsfiddle 中并添加了一些 css 规则以获得最小的示例工作。

HTML:

<section class="top-banner">
  <div class="flash-banner">
  </div>
</section>

CSS:

.top-banner {
    text-align: center;
    width: 100%;
    overflow: hidden;
}

.flash-banner {
    background: #2D3447;
    height: 121px;
    width: 50px;
    position: relative; 
  margin: 0 auto;
  padding: 0.25rem 30px;
  background: #333;
}

.flash-banner:before, 
.flash-banner:after {
  content: "";
  position: absolute;
  top: 0;
  bottom: 0;
  width: 9600px;
  right: 100%;
  background: red;
}

.flash-banner:after { 
  width: 9600px;
  left: 100%;
  background: green;
}

检查:https://jsfiddle.net/lmgonzalves/vwty760m/

试试这个

.flash-banner:before, 
.flash-banner:after {
  content: "";
  display: block;
  width: 50%;
  height: 100%;
  z-index:-1;
  position: absolute;
  top: 0;
  right: 0;
  background: green;
}

.flash-banner:after { 
  left: 0;
  background: red;
}

我已经调整了你的 :before:after 所以他们 运行 在 flash 横幅后面并 100% 填充它。

您需要做的就是更改 .flash-banner 的大小。

.top-banner {
  text-align: center;
  width: 100%;
  position: relative;
}

.flash-banner {
  height: 121px;
  width: 300px;
  background: blue;
  margin: auto;
  z-index: 1;
}

.flash-banner:before,
.flash-banner:after {
  content: "";
  position: absolute;
  width: 50%;
  height: 100%;
  left: 0;
  background: red;
  z-index: -1;
}

.flash-banner:after {
  background: green;
  right: 0;
  left: auto;
}
 <section class="top-banner">
  <div class="flash-banner">  
  </div>
</section>