首頁 >web前端 >css教學 >如何用CSS實作一個div內多種背景顏色?

如何用CSS實作一個div內多種背景顏色?

Linda Hamilton
Linda Hamilton原創
2024-11-15 05:53:02508瀏覽

How to Achieve Multiple Background Colors in One Div with CSS?

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.

以上是如何用CSS實作一個div內多種背景顏色?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn