Blended html and css

Режимы наложения слоёв в Web

Привет, Хабр!
Одна из главных причин тяжёлых увечий дизайнеров претензий к неопытным дизайнерам от верстальщиков, при получении от них PSD-макетов — это наличие слоёв с заданными режимами смешивания, отличными от normal. Вполне возможно, что скоро это уйдёт в прошлое!
Речь пойдёт о реализации спецификации «Compositing and Blending Level 1» в современных браузерах.

Что это и для чего?

Данный стандарт описывает правила наложения слоёв друг на друга, аналогично тому, как это делается в Photoshop. Например, в режиме multiply итоговый цвет пикселя будет равен произведению цветов двух слоёв. Благодаря этому, можно добиться различных эффектов, таких как:

1) Фотоэффекты, такие как обесцвечивание картинки, сепия, наложение цвета. Например, достаточно будет использовать только одну цветную картинку, чтобы получить плавную анимацию от обесцвеченной к цветной при наведении:
(по клику — живой пример на jsfiddle)

2) Часто дизайнеры ленятся вырезать фон из картинки и используют наложение картинки без прозрачности на слой так, что фоновый чёрный/белый цвет будет в данном режиме преобразуются в прозрачный (режим screen/multiply):

Читайте также:  Centering with css div

(на картинке внизу показал кусочек накладываемого изображения «как есть»)

3) Иногда можно использовать данную технологию для реализации эффектов с текстом, например, в логотипах:

Список режимов

Для примера будем накладывать тигра на такую картинку в разных режимах:

normal
multiply
screen
overlay
darken
lighten
color-dodge
color-burn
hard-light
soft-light
difference
exclusion
hue*
saturation*
color*
luminosity*

* здесь я взял раскрашенную в красные оттенки картинку, для демонстрации эффекта

Технологии применения и поддержка браузерами

По спецификации, применять режимы наложения можно в четырёх случаях:

1) Для фонового изображения в CSS

Поддерживают: Chrome 35+, Firefox 30+ beta (войдёт ли в релиз этот функционал, ещё вопрос, т. к. скорее всего уже переносили «приземление» этого функционала).

Поддерживают: пока нет, но активно идёт разработка по реализации.

Поддерживают: Chrome 35+, IE 10+ (с отличиями)

* доступны дополнительные режимы
Поддерживают: Chrome 29+, Firefox 24+, Opera 17+, Safari 6.1+

Узнать подробнее о поддержке браузерами данного стандарта можно в таблице от adobe.

Источник

Basics of CSS Blend Modes

Bennett Feely has been doing a good job of showing people the glory of CSS blend modes. There are lots of designerly effects that we’re used to seeing in static designs (thanks to Photoshop) that we don’t see on the web much, with dynamic content. But that will change as CSS blend modes get more support. I’d like to look at the different ways of doing it, since it’s not exactly cut and dry.

CSS Multiple Backgrounds Blend Modes

See the Pen Background Blending by Chris Coyier (@chriscoyier) on CodePen. Multiply is a nice and useful one, but there is also: screen , overlay , darken , lighten , color-dodge , color-burn , hard-light , soft-light , difference , exclusion , hue , saturation , color , and luminosity . And also normal which reset it. Adobe (who works on the spec for this stuff) created this Pen for playing with the different possiblities here. Update: they have removed that Pen, but do still have this explainer page. A single element can have more than one background, stacked up. Like:

Those can blend too simply by adding a background-blend-mode . See the Pen Multiple Background Blending by Chris Coyier (@chriscoyier) on CodePen. Here’s a cool and practical example by Bennett Feely: See the Pen rxoAc by Bennett Feely (@bennettfeely) on CodePen. Here’s another, which cleverly re-combines a color image separated into Cyan / Magenta / Yellow / Black parts (CMYK). You know that’s how offset lithography works in print, right? =) See the Pen CMY/CMYK Color printing with background-blend-mode by Bennett Feely (@bennettfeely) on CodePen.

Arbitrary HTML Elements Blend Modes

Blending backgrounds together is pretty cool, but personally I’m less excited about that than I am about blending arbitrary HTML elements together. Like a

title over a background, for example. Or even text over text. I saw this at an airport the other day and snapped a pic because I thought it looked neat and figured I could figure out how to do it on the web: My first attempt to recreate it, I used opacity. But opacity really dulls the colors and doesn’t make those overlapping bits have the extra darkness they should have. CJ Gammon showed me there is a blending property precicely for this purpose: mix-blend-mode . So to reproduce this:

Then squeeze the letters together with negative letter-spacing, set the mix-blend-mode, and colorize:

h1 < font-size: 7rem; font-weight: 700; letter-spacing: -1.25rem; >h1 span < mix-blend-mode: multiply; >h1 span:nth-child(1) < color: rgba(#AB1795, 0.75); >/* etc, on coloring */

Compare: See the Pen Overlapping Letters by Chris Coyier (@chriscoyier) on CodePen. Like I mentioned, real web text over image is a pretty sweet use case if you ask me: See the Pen GxlBm by Chris Coyier (@chriscoyier) on CodePen.

The DOM blend mode stuff is most interesting to me, but it should be noted that has blend modes as well and it has a bit deeper support (see below for all that). You set it on the canvas context. So like:

var canvas = document.getElementById('canvas'); var ctx = canvas.getContext('2d'); ctx.globalCompositeOperation = 'multiply';

That value can be any of those I listed above. Here’s a simple demo: See the Pen canvas blend modes by Chris Coyier (@chriscoyier) on CodePen. And a fancy one where you can see the blending give the demo life: See the Pen sketch.js Demo by Justin Windle (@soulwire) on CodePen.

As you might suspect, SVG does have its own mechanism for doing this. One way to do it is to define it within the itself, and it’s fairly complicated:

See the Pen Fnvdp by Chris Coyier (@chriscoyier) on CodePen. And a more complex example. The good news is that mix-blend-mode will work on inline SVG. So if you’re using SVG that way, you can target the shapes themselves with classes or whatever and give them whatever blend mode you want. Here’s an example by Bennet that does just that: See the Pen KDkCj by Bennett Feely (@bennettfeely) on CodePen.

For canvas: Firefox 20+, Chrome 30+, Safari 6.1+, Opera 17+, iOS 7+, Android 4.4+. Worst bad news: No IE. For HTML/CSS: Firefox 30+, Chrome 35+, Safari 6.1 (apparently not 7?). Not quite as supported as canvas. At this second, for Chrome, you’ll have to run Canary, go to chrome://flags/ and enable “experimental Web Platform features”. This actually it a bit more complicated, so if you really want to dig in and know about support, check out the Support Matrix from Adobe.

What is nice about blending is that the whole point is designerly effects. If they aren’t supported, you can take care to make sure the fallback is still readable (progressive enhancement!). Here’s a recent thought by Jeremy Keith:

It is entirely possible—nay, desirable—to use features long before they are supported in every browser. That’s how we move the web forward.

So one way to do support is to look at the design in a non-supporting browser and if it is still readable/usable, you’re good, no further action required. If the result ends up unreadable/unusable, you could tweak things around until they are, or run a test to determine support and do something specific in the case of non-support. To test for support, I guess you could do test for the property you want to use:

var supportsMixBlendMode = window.getComputedStyle(document.body).mixBlendMode; var supportsBackgroundBlendMode = window.getComputedStyle(document.body).backgroundBlendMode;

If the returned value is “normal” (or anything other than undefined ) support is there, otherwise not. Then probably apply a class to the element so you can know that and use it anywhere in your CSS to adjust things, Modernizr style. Perhaps they’ll even do a test for it in the future. Unless it’s not that simple in which case let me know. Need more ideas? Check out this collection. Happy blending!

Источник

mix-blend-mode¶

Свойство mix-blend-mode опреляет режим смешивания цветов выбранного элемента с низлежащими слоями.

Демо¶

  • contain
  • contain-intrinsic-block-size
  • contain-intrinsic-height
  • contain-intrinsic-inline-size
  • contain-intrinsic-size
  • contain-intrinsic-width
  • container
  • container-name
  • container-type
  • @container
  • content-visibility

Синтаксис¶

 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
/* Ключевые слова */ mix-blend-mode: normal; mix-blend-mode: multiply; mix-blend-mode: screen; mix-blend-mode: overlay; mix-blend-mode: darken; mix-blend-mode: lighten; mix-blend-mode: color-dodge; mix-blend-mode: color-burn; mix-blend-mode: hard-light; mix-blend-mode: soft-light; mix-blend-mode: difference; mix-blend-mode: exclusion; mix-blend-mode: hue; mix-blend-mode: saturation; mix-blend-mode: color; mix-blend-mode: luminosity; /* Глобальные значения */ mix-blend-mode: initial; mix-blend-mode: inherit; mix-blend-mode: unset; 

Значения¶

Спецификация¶

Описание и примеры¶

normal multiply screen overlay darken lighten color-dodge color-burn hard-light soft-light difference exclusion hue saturation color luminosity

Normal blend mode

Конечный цвет — это верхний цвет, независимо от того, что представляет собой нижний цвет. Эффект подобен двум непрозрачным кускам бумаги, перекрывающимся друг над другом.

Multiply blend mode

Конечный цвет — результат умножения верхнего и нижнего цветов. Черный слой приводит к черному окончательному слою, а белый слой не приводит к изменению. Эффект подобен двум изображениям, нанесенным на прозрачную пленку.

Screen blend mode

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

Overlay blend mode

Конечный цвет — результат multiply , если нижний цвет темнее или screen , если нижний цвет светлее. Этот режим смешивания эквивалентен hard-light , но со слоем обмена.

Darken blend mode

Конечный цвет состоит из самых темных значений каждого цветового канала.

Lighten blend mode

Конечный цвет состоит из самых светлых значений каждого цветового канала.

Color-dodge blend mode

Конечный цвет — результат деления нижнего цвета на обратный верхний цвет. Черный передний план не приводит к изменению. Передний план с обратным цветом фона приводит к полностью освещенному цвету.

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

Color-burn blend mode

Конечный цвет является результатом инвертирования нижнего цвета, деления значения на верхний цвет и инвертирования этого значения. Белый передний план не дает никаких изменений. Передний план с обратным цветом фона приводит к черному окончательному изображению.

Этот режим смешивания аналогичен multiply , но переднего плана нужно только быть темным, как обратное к фону, чтобы сделать окончательное изображение черным.

Hard-light blend mode

Конечный цвет — результат multiply , если верхний цвет темнее или screen , если верхний цвет светлее. Этот режим смешивания эквивалентен overlay , но со слоем обмена. Эффект подобен сиянию сурового прожектора на заднем плане.

Soft-light blend mode

Конечный цвет похож на hard-light , но мягче. Этот режим смешивания ведет себя аналогично hard-light . Эффект подобен сиянию рассеянного прожектора на заднем плане.

Difference blend mode

Конечный цвет — результат вычитания более темного из двух цветов из более светлого. Черный слой не действует, а белый слой инвертирует цвет другого слоя.

Exclusion blend mode

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

Hue blend mode

Конечный цвет имеет оттенок верхнего цвета, используя насыщенность и светимость нижнего цвета.

Saturation blend mode

Конечный цвет имеет насыщенность верхнего цвета, используя оттенок и светимость нижнего цвета. Чистый серый фон, без насыщения, не будет иметь никакого эффекта.

Color blend mode

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

Luminosity blend mode

Конечный цвет имеет яркость верхнего цвета, используя оттенок и насыщенность нижнего цвета. Этот режим смешивания эквивалентен color , но при этом слои меняются местами.

Пример¶

svg> circle cx="40" cy="40" r="40" fill="cyan" /> circle cx="80" cy="40" r="40" fill="magenta" /> circle cx="60" cy="80" r="40" fill="yellow" /> svg> 
circle  mix-blend-mode: multiply; > 

Источник

Оцените статью