首頁 > web前端 > css教學 > 主體

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

Linda Hamilton
發布: 2024-11-15 05:53:02
原創
434 人瀏覽過

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中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板