首頁 > web前端 > css教學 > 如何根據背景顏色反轉 CSS 字體顏色?

如何根據背景顏色反轉 CSS 字體顏色?

Barbara Streisand
發布: 2024-12-17 15:25:20
原創
662 人瀏覽過

How Can I Invert CSS Font Color Based on Background Color?

根據背景顏色反轉CSS 字體顏色

在CSS 中,沒有直接屬性允許您根據背景顏色反轉字體顏色背景顏色。但是,您可以利用多種技術來實現此效果。

使用偽元素

偽元素可用於在文字周圍創建包裝,這然後你就可以獨立設計風格了。例如:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

.inverted-bar {

    position: relative;

}

 

.inverted-bar:before,

.inverted-bar:after {

    padding: 10px 0;

    text-indent: 10px;

    position: absolute;

    white-space: nowrap;

    overflow: hidden;

    content: attr(data-content);

}

 

.inverted-bar:before {

    background-color: aqua;

    color: red;

    width: 100%;

}

 

.inverted-bar:after {

    background-color: red;

    color: aqua;

    width: 20%;

}

登入後複製

使用兩個 DIV

對於不支援偽元素的舊版瀏覽器,您可以使用兩個 DIV:

1

<div class="inverted-bar" data-content="Lorem ipsum dolor sit amet"></div>

登入後複製

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

.inverted-bar {

    position: relative;

    padding: 10px;

    text-indent: 10px;

}

 

.inverted-bar:before {

    content: attr(data-content);

    background-color: aqua;

    color: red;

    position: absolute;

    top: 0;

    left: 0;

    z-index: 1;

    white-space: nowrap;

    overflow: hidden;

    padding: 10px 0;

    width: 100%;

}

 

.inverted-bar > div {

    content: attr(data-content);

    background-color: red;

    color: aqua;

    position: absolute;

    padding: 10px 0;

    top: 0;

    left: 0;

    width: 20%;

}

登入後複製

注意:具體實作可能會有所不同取決於您的特定要求和瀏覽器支援。

以上是如何根據背景顏色反轉 CSS 字體顏色?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

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