」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 如何根據背景顏色反轉 CSS 字體顏色?

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

發佈於2024-12-22
瀏覽:733

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

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

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

使用偽元素

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

.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:

.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%;
}

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

最新教學 更多>

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3