开发者

Multiple background colours on 1 DIV

开发者 https://www.devze.com 2023-04-11 04:51 出处:网络
I have a div, and I would like to apply 2 backgrounds horizontally onto it using CSS3, but I can\'t figure it out, and so I would appreciate any help!

I have a div, and I would like to apply 2 backgrounds horizontally onto it using CSS3, but I can't figure it out, and so I would appreciate any help!

    background: blue top no-repeat 10%;
    background: yellow bottom no-repeat 10%;

I want the top half to be one color, and the bottom half to be a di开发者_Go百科fferent colour.

I know it can be done quite easily with images, but I just can't figure out how to do this without using them.


A gradient is a reasonably simple way to do this using CSS3 and only one div:

http://jsfiddle.net/thirtydot/8wH2F/

Yes, I lied. It's not very simple at all due to the myriad different vendor prefixed versions of the same thing that you need to use:

div {
    background: #000fff; /* Old browsers */
    background: -moz-linear-gradient(top, #000fff 0%, #000fff 50%, #ffff00 50%, #ffff00 100%); /* FF3.6+ */
    background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#000fff), color-stop(50%,#000fff), color-stop(50%,#ffff00), color-stop(100%,#ffff00)); /* Chrome,Safari4+ */
    background: -webkit-linear-gradient(top, #000fff 0%,#000fff 50%,#ffff00 50%,#ffff00 100%); /* Chrome10+,Safari5.1+ */
    background: -o-linear-gradient(top, #000fff 0%,#000fff 50%,#ffff00 50%,#ffff00 100%); /* Opera11.10+ */
    background: -ms-linear-gradient(top, #000fff 0%,#000fff 50%,#ffff00 50%,#ffff00 100%); /* IE10+ */
    background: linear-gradient(top, #000fff 0%,#000fff 50%,#ffff00 50%,#ffff00 100%); /* W3C */
}

I generated the CSS here, and removed the filter property since it will result in an actual gradient in IE6-9.


Another way to achieve this, apart from the gradients, is to use pseudo-element:

http://jsfiddle.net/kizu/S3LXB/

Add position: relative and some positive z-index to the element and the negative z-index to the pseudo-element, and it would be placed over the element's background, but under the element's content. And then you can position in just how you want.

This way is not as flexible as the one with gradients, but! You can for sure use the gradients for the pseudo-element and so achieve even more effects more easily.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号