How to make a background using CSS gradient with f

2019-06-15 16:04发布

A backgrond like this with same height of red and yellow.

enter image description here

标签: css3 gradient
2条回答
姐就是有狂的资本
2楼-- · 2019-06-15 16:37

Using Colorzilla's gradient generator, just set two colors to the same % location and you'll get a hard edge between the two colors.

background: #ffff00; /* Old browsers */
background: -moz-linear-gradient(top, #ffff00 30%, #ffff00 30%, #fe0000 30%); /*  FF3.6+ */
background: -webkit-gradient(linear, left top, left bottom, color-stop(30%,#ffff00), color-stop(30%,#ffff00), color-stop(30%,#fe0000)); /* Chrome,Safari4+ */
background: -webkit-linear-gradient(top, #ffff00 30%,#ffff00 30%,#fe0000 30%); /* Chrome10+,Safari5.1+ */
background: -o-linear-gradient(top, #ffff00 30%,#ffff00 30%,#fe0000 30%); /* Opera11.10+ */
background: -ms-linear-gradient(top, #ffff00 30%,#ffff00 30%,#fe0000 30%); /* IE10+ */
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#ffff00', endColorstr='#fe0000',GradientType=0 ); /* IE6-9 */
background: linear-gradient(top, #ffff00 30%,#ffff00 30%,#fe0000 30%); /* W3C */
查看更多
【Aperson】
3楼-- · 2019-06-15 16:43

Colorzilla's gradient generator is a nice start, but the code is awful in my opinion.
You'll never easily see if the colors are right, there's no output of short hex codes like #ff0 and – most important in comparison to the answer above – the W3C standard has changed to to <side-or-corner>.

So given your question after a flat gradient with same height of red and yellow area this is my preferred code:

background-color: #ff0; /* Old browsers */
background-image: -webkit-gradient( linear, left top, left bottom, color-stop( 50%, #ff0 ), color-stop( 50%, #ff0 ), color-stop( 50%, #fe0000 ) ); /* Chrome, Safari4+ */
background-image: -webkit-linear-gradient( top, #ff0 50%, #ff0 50%, #fe0000 50% ); /* Chrome10+, Safari5.1+ */    
background-image:    -moz-linear-gradient( top, #ff0 50%, #ff0 50%, #fe0000 50% ); /* Fx3.6+ */   
background-image:         linear-gradient(      #ff0 50%, #ff0 50%, #fe0000 50% ); /* W3C */

See example on CodePen.

Also note, that you can leave out the deprecated filter property for IEs in this case, simply because there are no color stops included.
If you know the exact height of the box, you could also work with px values instead of the % values for the color stops.

Updated 2016-01-16: Neither -o- vendor prefix is necessary, nor -ms- (as IE 10 is the first IE to support gradients and it does support the W3C standards syntax). See http://caniuse.com/#feat=css-gradients
Updated 2016-01-27: Prefer lowercase hex color values for better gzipping, and clearly state background-color and background-image instead of background. Also removed to bottom as it's the default value.

查看更多
登录 后发表回答