Lepistina's Code Café

How to divide a div into two colors with CSS

Written by on November 1, 2017

Recently I ran into a problem of needing to split a div into two colors, horizontally.

Here is the mockup:

 

I tried several ways to implement it but always ran into a responsiveness problem (making it look good on different screen sizes).

Finally, the solution was found! If you wonder how I implemented it, you can check out the final project on my portfolio http://lepistina.com/projects/medical/index.html .

I divided the div into two colors with the CSS property background and its value linear-gradient. I used percentages to control how much of white and how much of blue colors I want to show in my div.

You would probably think that using linear-gradient, will mean that the point of meeting two colors will be blurry. Yes, it could, but we can also use percentages to control how we want the point of meeting two colors to look like.

.split-bg {
 background: #F0F5F6; /* Old browsers */
 background: -moz-linear-gradient(top,  #FFF 0%, #FFF 30%, #F0F5F6 30%, #F0F5F6 100%); /* FF3.6+ */
 background: -webkit-gradient(linear, left top, right top, color-stop(0%,#FFF), color-stop(30%,#FFF), color-stop(30%,#F0F5F6), color-stop(100%,#F0F5F6)); /* Chrome,Safari4+ */
 background: -webkit-linear-gradient(top,  #FFF 0%,#FFF 30%,#F0F5F6 30%,#F0F5F6 100%); /* Chrome10+,Safari5.1+ */
 background: -o-linear-gradient(top,  #FFF 0%,#FFF 30%,#F0F5F6 30%,#F0F5F6 100%); /* Opera 11.10+ */
 background: -ms-linear-gradient(top,  #FFF 0%,#FFF 30%,#F0F5F6 30%,#F0F5F6 100%);  /*IE10+*/
 background: linear-gradient(to bottom,  #FFF 0%,#FFF 30%,#F0F5F6 30%,#F0F5F6 100%); /* W3C */
}

Note: To make your style to be browser compatible, use the browser prefixes (ex.  -ms-);

Here is a simple example in jsfiddle:

https://jsfiddle.net/Lepistina/tdbwboy5/1/

I found the following tutorials on this subject very helpful:

 

I hope it was helpful.

Thank you for reading my blog post.

Categories: Coding

Share your thoughts!

Your email address will not be published. Required fields are marked *