试图在“一分为二”的页面上实现背景;两种相对的颜色(似乎是通过在body标签上设置默认的背景色来完成的,然后将另一种颜色应用到扩展整个窗口宽度的div上)。

我确实提出了一个解决方案,但不幸的是,背景大小的属性不工作在IE7/8,这是一个必须为这个项目-

body { background: #fff; }
#wrapper {
    background: url(1px.png) repeat-y;
    background-size: 50% auto;
    width: 100%;
}

既然它只是关于纯色,也许有一种方法只使用常规的背景颜色属性?


当前回答

最可靠且语义正确的选项是使用定位固定的伪元素(::after或::before)。使用这种技术时,不要忘记为容器内的元素设置z-index。还要注意,伪元素的content:""规则是需要的,否则它不会被渲染。

#container {...}

#content::before {
    content:"";
    background-color: #999;
    height: 100%;
    left: 0px;
    position: fixed;
    top: 0px;    
    width: 50%; 
    z-index: 1;
}


#content * {
  position: relative;
  z-index:2;
}

生活例子: https://jsfiddle.net/xraymutation/pwz7t6we/16/

其他回答

所以,这是一个非常古老的问题,已经有了一个公认的答案,但我相信,如果这个答案是在四年前发布的,它就会被选中。

我完全用CSS解决了这个问题,没有额外的DOM元素!这意味着这两种颜色是纯粹的,只是一个元素的背景色,而不是两个元素的背景色。

我使用了渐变,因为我把颜色设置得非常接近,所以看起来好像颜色是不同的,它们没有混合。

下面是原生语法中的梯度:

background: repeating-linear-gradient(#74ABDD, #74ABDD 49.9%, #498DCB 50.1%, #498DCB 100%);

颜色#74ABDD开始为0%,仍然为#74ABDD为49.9%。

然后,我强制渐变到元素高度的0.2%以内的下一个颜色,在两个颜色之间创建一个看起来非常坚实的线。

结果如下:

这是我的JSFiddle!

玩得开心!

如果你想使用50%高度的线性梯度:

background: linear-gradient(to bottom, red 0%, blue 100%) no-repeat;
background-size: calc(100%) calc(50%);
background-position: top;

这应该与纯css工作。

background: -webkit-gradient(linear, left top, right top, color-stop(50%,#141414), color-stop(50%,#333), color-stop(0%,#888));

仅在Chrome中测试。

实现你的问题的一种方法是添加一行到你的div的css:

background-image: linear-gradient(90deg, black 50%, blue 50%);

这里是一个演示代码和更多选项(水平,对角线等),你可以点击“运行代码片段”来查看它的现场。

.abWhiteAndBlack { background-image: linear-gradient(90deg, black 50%, blue 50%); height: 300px; width: 300px; margin-bottom: 80px; } .abWhiteAndBlack2 { background-image: linear-gradient(180deg, black 50%, blue 50%); height: 300px; width: 300px; margin-bottom: 80px; } .abWhiteAndBlack3 { background-image: linear-gradient(45deg, black 50%, blue 50%); height: 300px; width: 300px; margin-bottom: 80px; } Vertical: <div class="abWhiteAndBlack"> </div> Horizonal: <div class="abWhiteAndBlack2"> </div> Diagonal: <div class="abWhiteAndBlack3"> </div>

使用在你的图像bg

垂直分割

background-size: 50% 100%

水平中分面

background-size: 100% 50%

例子

.class {
   background-image: url("");
   background-color: #fff;
   background-repeat: no-repeat;
   background-size: 50% 100%;
}