背景颜色50%是一种颜色,另外50%是另一种颜色

18
在一个
标签内,我想在它的前50%设置背景颜色,在其后50%设置另一种颜色。最好的情况是,在调整大小时无缝地调整,不会出现任何伪像或抖动效果。
理想情况下,我想避免在代码中使用其他
标签,因为我正在处理难以更改的现有HTML - 真正寻找100% CSS解决方案。
我想要类似于这样的东西(我用Fireworks制作了这个示意图): enter image description here
5个回答

40

您可以使用类似的方法,但根据您需要支持的浏览器,它可能无法在所有浏览器上都有效。

background: linear-gradient(to left, #ff0000 50%, #0000ff 50%);

5
您可以使用:before和:after伪元素。
#somediv {
  width:50%;
  height:100px;
  position: relative;
}

#somediv:after, #somediv:before {
  content:' ';
  position: absolute;
  width:50%;
  height:100%;
  z-index: -1;
}

#somediv:after {left: 0px; background: #F00;  }
#somediv:before {right: 0px; background: #00F;}

编辑:像这样http://plnkr.co/edit/hm9bHNuuzh2EK4zwn3nr?p=preview

即使在IE8中也可以使用,而渐变效果则无法实现。

如果您需要更加贴合您的需求,请告诉我。


3

http://jsfiddle.net/Rn8PZ/

div {
    background: -webkit-linear-gradient(right, tan 50%, green 50%);
    background: -o-linear-gradient(right, tan 50%, green 50%);
    background: -moz-linear-gradient(right, tan 50%, green 50%);
    background: linear-gradient(to right, tan 50%, green 50%);
}

这应该被接受为正确(最佳)答案。 - karlo1zg

2
您可以使用渐变,像这样:http://jsfiddle.net/F3M5e/ 相关代码:
background: #1e5799; /* Old browsers */
background: -moz-linear-gradient(top,  #1e5799 0%, #1e5799 50%, #000000 50%, #000000 100%); /* FF3.6+ */
background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#1e5799), color-stop(50%,#1e5799), color-stop(50%,#000000), color-stop(100%,#000000)); /* Chrome,Safari4+ */
background: -webkit-linear-gradient(top,  #1e5799 0%,#1e5799 50%,#000000 50%,#000000 100%); /* Chrome10+,Safari5.1+ */
background: -o-linear-gradient(top,  #1e5799 0%,#1e5799 50%,#000000 50%,#000000 100%); /* Opera 11.10+ */
background: -ms-linear-gradient(top,  #1e5799 0%,#1e5799 50%,#000000 50%,#000000 100%); /* IE10+ */
background: linear-gradient(to bottom,  #1e5799 0%,#1e5799 50%,#000000 50%,#000000 100%); /* W3C */
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#1e5799', endColorstr='#000000',GradientType=0 ); /* IE6-9 */

编辑:水平渐变 http://jsfiddle.net/F3M5e/1/


0

.background{
 background: -webkit-linear-gradient(top, #2897e0 40%, #F1F1F1 40%);
 height:200px;
 
}

.background2{
  background: -webkit-linear-gradient(right, #2897e0 50%, #28e09c 50%);

 height:200px;
 
}
<html>
<body class="one">

<div class="background">
</div>
<div class="background2">
</div>
</body>
</html>


请解释这个回答如何回答了问题。 - Pierre.Vriens
问题是:在一个 div 中,我想在其宽度的前 50% 放置背景颜色,在其宽度的另外 50% 放置另一种颜色。因此,我使用了属性 -webkit-linear-gradient(right, color 50%, color 50%)。 - Seth

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接