Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Different background-color for left and right half of div

I have a centered div layout. The left side of the div in the background should be white and the right side should be green. Both should extend to infinity.

I think it should be quite simple but I just don't get it right now. Any easy solution? Thank you!

-----------------------------------------------------
(div 1)     __________________________ 
           |(div 2)         |         |
           |                |         |
           |                |         |
<- white   |     white      |  green  |   green  ->
           |                |         |
           |                |         |
           |________________|_________|

------------------------------------------------------
like image 876
Christoph Avatar asked Aug 14 '09 11:08

Christoph


People also ask

How do you add a half background color in HTML?

To achieve this, use a color value which has an alpha channel—such as rgba. As with opacity , a value of 1 for the alpha channel value makes the color fully opaque. Therefore background-color: rgba(0,0,0,. 5); will set the background color to 50% opacity.

How do I have two background colors in CSS?

CSS allows you to add multiple background images for an element, through the background-image property. The different background images are separated by commas, and the images are stacked on top of each other, where the first image is closest to the viewer.


2 Answers

Use the ::after and ::before psuedo elements. That way you can even get three colors and do the Italian flag!

div {
    height:300px;
    width:100%;
    outline:thin solid black;
    position:relative;
    background:white;
}
div::after, div::before {
    height:300px;
    content:' ';
    position: absolute;
    top: 0;
    width: 33%;
}
div::after {
    right: 0;
    background-color: red;
}
div::before {
    left: 0;
    background-color: green;
}

Here's a fiddle: http://jsfiddle.net/g8p9pn1v/

And its results: enter image description here

like image 99
Shaun Luttin Avatar answered Sep 18 '22 17:09

Shaun Luttin


Add a background image with the two colors to the outer div and allow the browser to scale it (instead of tiling it).

Each color should fill exactly 50% of the width of the image to make sure the colors will never leak on either side.

Maybe even position the image absolutely behind the inner div.

For ideas how to stretch the image, see this question: CSS Background Repeat

like image 29
Aaron Digulla Avatar answered Sep 21 '22 17:09

Aaron Digulla