Инвертировать шрифт CSS в зависимости от цвета фона - программирование
Подтвердить что ты не робот

Инвертировать шрифт CSS в зависимости от цвета фона

Есть ли свойство CSS для инвертирования font-color зависимости от background-color как на этой картинке?

enter image description here

4b9b3361

Ответ 1

Существует свойство CSS, называемое mix-blend-mode, но оно не поддерживается IE. Я рекомендую использовать псевдоэлементы. Если вам нравится поддерживать IE6 и IE7, вы также можете использовать два DIV вместо псевдоэлементов.

enter image description here

.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 class="inverted-bar" data-content="Lorem ipsum dolor sit amet"></div>

Ответ 2

Да, сейчас есть. Используя mix-blend-mode, это можно сделать с помощью CSS.

blend-modes example

http://jsfiddle.net/1uubdtz6/

div {
    position:absolute;
    height:200px
}

/* A white bottom layer */
#whitebg { 
    background: white; 
    width:400px; 
    z-index:1
}

/* A black layer on top of the white bottom layer */
#blackbg { 
    background: black; 
    width:100px; 
    z-index:2
}

/* Some white text on top with blend-mode set to 'difference' */
span {
    position:absolute; 
    font-family: Arial, Helvetica; 
    font-size: 100px; 
    mix-blend-mode: difference;
    color: white;
    z-index: 3
}

/* A red DIV over the scene with the blend-mode set to 'screen' */
#makered { 
    background-color: red;
    mix-blend-mode: screen;
    width:400px; 
    z-index:4
}
<div id="whitebg"></div>
<div id="blackbg"></div>
<div id="makered"></div>

<span>test</span>

Ответ 3

Я знаю, что это старый вопрос, но я хотел добавить еще одно решение, которое я использовал, прежде чем я узнал о mix-blend-mode.

Идея состоит в том, чтобы дублировать информацию в два слоя: фон и передний план, где фон и передний план имеют разные цвета фона и текста. Они идентичны по размеру и тексту. Между ними я использую блок обрезки div чтобы обрезать верхний слой до желаемой ширины, показывая верхний слой, где он не обрезан, и показывая фоновый слой за пределами окна обрезки.

Это похоже на решение "Два деления" в принятом ответе, но использует дополнительное поле отсечения. Это позволяет легко центрировать текст, если это необходимо, и простой, прямой выбор цветов.

HTML:

<div class='progress' id='background'>
  <span></span>
  <div class='progress' id='boundbox'>
    <div class='progress' id='foreground'>
    </div>
  </div>
</div>

CSS (извиняюсь за запутанные имена идентификаторов, "background" и "foreground"):

.progress {
  display: block;
  margin: 0;

  /* Choose desired padding/height in coordination with font size */
  padding: 10px;
  height: 28px;
}

#background {
  position: relative;

  /* Choose a border to your liking, or none */
  border: 1px solid lightgray;

  /* Choose your desired text attributes */
  text-align: center;
  font-family: Calibri, "Sans Serif";
  font-size: 16pt;

  /* Set the desired width of the whole progress bar */
  width: 75%;

  /* Choose the desired background and text color */
  background-color: white;
  color: black;
}

#foreground {
  position: absolute;
  left: 0;
  top: 0;

  /* Choose the desired background and text colors */
  background-color: navy;
  color: white;
}

#boundbox {
  position: absolute;
  left: 0;
  top: 0;
  overflow: hidden;
}

Я использую jQuery, чтобы программно установить процент выполнения и убедиться, что ширина переднего плана совпадает с шириной фона, и что у них одинаковый текст. Это также легко сделать с помощью чистого Javascript.

// Set foreground width to background width
// Do this after DOM is ready
$('#foreground').width($('#background').width())

// Based upon an event that determines a content change
// you can set the text as in the below example
percent_complete = 45   /* Compute a % complete value */
$('#foreground').text('${percent_complete}% complete')
$('#background span').text($('#foreground').text())
$('#boundbox').css('width', '${percent_complete}%')

А вот скрипка: Прогресс-бар.

enter image description here

Я проверял это в Chrome, Firefox и Microsoft Edge.

Ответ 4

Я думаю, что это проще понять.

*{
    margin: 0;
    padding: 0;
    box-sizing: border-box;
    font-family: sans-serif;
}
.titulo{
    text-align: center;
    margin: 2em;
}
.padre{
    margin: 0 auto;
    display: flex;
    justify-content: center;
    align-items: center;
    margin-top: 10em;
    position: relative;
    width: 1000px;
    height: 500px;
}
.caja-1{
    background-color: black;
    width: 500px;
    height: 500px;
    left: 0;
    mix-blend-mode: screen;
    position:absolute;
}
.caja-3{
    width: 500px;
    height: 500px;
    display: flex;
    background-color: white;
    position: absolute;
    right: 0;
}
.texto{
    font-size: 5em;
    color: white;
    mix-blend-mode: difference;
    position:absolute;
}
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>ESTILOS CONTRASTADOS CSS3</title>
</head>
<body>
    <h1 class="titulo">MIX-BLEND-MODE CSS EFFECT</h1>
    <div class="padre">
        <div class="caja-1"></div>
        <div class="caja-3"></div>
        <h1 class="texto">CODE STOCK CENTER</h1>
    </div>
</body>
</html>