How to make a background using CSS gradient with flat color?

我的未来我决定 提交于 2019-12-10 12:34:23

问题


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


回答1:


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 */



回答2:


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.



来源:https://stackoverflow.com/questions/7108603/how-to-make-a-background-using-css-gradient-with-flat-color

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!