How to Achieve Multiple Background Colors in a Single Div with CSS?

Susan Sarandon
Release: 2024-11-16 11:06:03
Original
362 people have browsed it

How to Achieve Multiple Background Colors in a Single Div with CSS?

Multiple Background Colors for a Single div

In certain scenarios, applying multiple background colors to a div is advantageous over using background images or additional divs. CSS provides various ways to achieve this effect.

1. Linear-Gradient for Two or More Colors:

To create "A" with two colors, as illustrated in the image, use a linear gradient with four positions:

background: linear-gradient(to right, #9c9e9f 0%, #9c9e9f 50%, #f6f6f6 50%, #f6f6f6 100%);
Copy after login

2. Creating a Smaller Portion for "C":

For "C," use a linear gradient similar to "A," but add a :after selector with a white background to simulate a smaller blue portion:

background: linear-gradient(to right, #9c9e9f 0%, #9c9e9f 50%, #33ccff 50%, #33ccff 100%);
.c:after {
    content: "";
    position: absolute;
    right: 0;
    bottom: 0;
    width: 50%;
    height: 20%;
    background-color: white;
}
Copy after login

Improved Alternative for "C":

The previous solution creates an overlapping effect with the white portion. A better alternative is to use the 'background-clip' property, which allows you to clip the background to the specified shape:

background: linear-gradient(to right, #9c9e9f 0%, #9c9e9f 50%, #33ccff 50%, #33ccff 100%);
background-clip: border-box;
Copy after login

The above is the detailed content of How to Achieve Multiple Background Colors in a Single Div with CSS?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template