Achieving Multiple Background Colors in One Div
In CSS, applying multiple background colors to a single div can be achieved through various techniques. Let's explore some options with different scenarios.
Scenario 1: Div with Two Equal Portions
To create a div with two equal portions, each with a different color, linear gradients can be used. For example, to achieve the effect shown in "A" of your image, you can employ the following CSS:
div.A { background: linear-gradient(to right, #9c9e9f 0%, #9c9e9f 50%, #f6f6f6 50%, #f6f6f6 100%); }
This gradient uses four positions to specify the color transition. The first and second positions define the dark grey color from 0% to 50%, and the third and fourth positions define the light grey color from 50% to 100%.
Scenario 2: Div with Unequal Portions
To create a div with portions of different heights, you can combine linear gradients with pseudo-elements. For example, to achieve the effect shown in "C" of your image, where the blue portion is smaller in height than the other portion, use the following CSS:
div.C { background: linear-gradient(to right, #9c9e9f 0%, #9c9e9f 50%, #33ccff 50%, #33ccff 100%); } div.C:after { content: ""; position: absolute; right: 0; bottom: 0; width: 50%; height: 20%; background-color: white; }
In this scenario, a pseudo-element (:after) is added to the div. This element acts as the "smaller" blue portion. It is positioned absolutely at the bottom-right corner of the div, with a width of 50% and a height of 20%. The background-color is set to white, which overlaying the blue portion to achieve the desired effect.
The above is the detailed content of How to Achieve Multiple Background Colors in One Div with CSS?. For more information, please follow other related articles on the PHP Chinese website!