grayscale()

grayscale()

Функция grayscale() превращает изображение в чёрно-белое.

Синтаксис

Синтаксис

Описание Пример
Указывает тип значения.
A && B Значения должны выводиться в указанном порядке. &&
A | B Указывает, что надо выбрать только одно значение из предложенных (A или B). normal | small-caps
A || B Каждое значение может использоваться самостоятельно или совместно с другими в произвольном порядке. width || count
[ ] Группирует значения. [ crop || cross ]
* Повторять ноль или больше раз. [,]*
+ Повторять один или больше раз. +
? Указанный тип, слово или группа не является обязательным. inset?
Повторять не менее A, но не более B раз.
# Повторять один или больше раз через запятую. #

Значения

Значение 100% или 1 превращает изображение в чёрно-белое. Значение 0 оставляет изображение исходно цветным. Значения меньше 100% (или меньше 1) линейно меняют цветность картинки.

Отрицательное значение не допускается. Пустое значение воспринимается как 0.

Песочница

Пример

grayscale()

.grayscale < filter: grayscale(100%); transition: 1s; >.grayscale:hover

Результат данного примера показан на рис. 1. При наведении курсора мыши на фотографию, она плавно из чёрно-белой превращается в цветную.

Чёрно-белые изображения

Рис. 1. Чёрно-белые изображения

Примечание

Chrome до версии 53, Opera до версии 40 и Safari до версии 9.1 поддерживают свойство -webkit-filter .

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

Каждая спецификация проходит несколько стадий одобрения.

  • Recommendation ( Рекомендация ) — спецификация одобрена W3C и рекомендована как стандарт.
  • Candidate Recommendation ( Возможная рекомендация ) — группа, отвечающая за стандарт, удовлетворена, как он соответствует своим целям, но требуется помощь сообщества разработчиков по реализации стандарта.
  • Proposed Recommendation ( Предлагаемая рекомендация ) — на этом этапе документ представлен на рассмотрение Консультативного совета W3C для окончательного утверждения.
  • Working Draft ( Рабочий проект ) — более зрелая версия черновика после обсуждения и внесения поправок для рассмотрения сообществом.
  • Editor’s draft ( Редакторский черновик ) — черновая версия стандарта после внесения правок редакторами проекта.
  • Draft ( Черновик спецификации ) — первая черновая версия стандарта.

Браузеры

В таблице браузеров применяются следующие обозначения.

  • — элемент полностью поддерживается браузером;
  • — элемент браузером не воспринимается и игнорируется;
  • — при работе возможно появление различных ошибок, либо элемент поддерживается с оговорками.

Число указывает версию браузреа, начиная с которой элемент поддерживается.

См. также

Рецепты

Справочник CSS

  • !important
  • ::after
  • ::backdrop
  • ::before
  • ::first-letter
  • ::first-line
  • ::placeholder
  • ::selection
  • :active
  • :blank
  • :checked
  • :default
  • :disabled
  • :empty
  • :enabled
  • :first-child
  • :first-of-type
  • :focus
  • :focus-within
  • :fullscreen
  • :hover
  • :in-range
  • :indeterminate
  • :invalid
  • :lang
  • :last-child
  • :last-of-type
  • :link
  • :not
  • :nth-child
  • :nth-last-child
  • :nth-last-of-type
  • :nth-of-type
  • :only-child
  • :only-of-type
  • :optional
  • :out-of-range
  • :placeholder-shown
  • :read-only
  • :read-write
  • :required
  • :root
  • :target
  • :valid
  • :visited
  • @charset
  • @document
  • @font-face
  • @import
  • @keyframes
  • @media
  • @page
  • @supports
  • @viewport
  • accent-color
  • align-content
  • align-items
  • align-self
  • all
  • animation
  • animation-delay
  • animation-direction
  • animation-duration
  • animation-fill-mode
  • animation-iteration-count
  • animation-name
  • animation-play-state
  • animation-timing-function
  • aspect-ratio
  • backdrop-filter
  • backface-visibility
  • background
  • background-attachment
  • background-blend-mode
  • background-clip
  • background-color
  • background-image
  • background-origin
  • background-position
  • background-position-x
  • background-position-y
  • background-repeat
  • background-size
  • block-size
  • border
  • border-bottom
  • border-bottom-color
  • border-bottom-left-radius
  • border-bottom-right-radius
  • border-bottom-style
  • border-bottom-width
  • border-collapse
  • border-color
  • border-image
  • border-left
  • border-left-color
  • border-left-style
  • border-left-width
  • border-radius
  • border-right
  • border-right-color
  • border-right-style
  • border-right-width
  • border-spacing
  • border-style
  • border-top
  • border-top-color
  • border-top-left-radius
  • border-top-right-radius
  • border-top-style
  • border-top-width
  • border-width
  • bottom
  • box-decoration-break
  • box-shadow
  • box-sizing
  • caption-side
  • caret-color
  • clear
  • clip
  • color
  • column-count
  • column-fill
  • column-gap
  • column-rule
  • column-rule-color
  • column-rule-style
  • column-rule-width
  • column-span
  • column-width
  • columns
  • content
  • counter-increment
  • counter-reset
  • cursor
  • direction
  • display
  • empty-cells
  • filter
  • flex
  • flex-basis
  • flex-direction
  • flex-flow
  • flex-grow
  • flex-shrink
  • flex-wrap
  • float
  • font
  • font-family
  • font-kerning
  • font-size
  • font-stretch
  • font-style
  • font-variant
  • font-weight
  • height
  • hyphens
  • image-rendering
  • justify-content
  • left
  • letter-spacing
  • line-clamp
  • line-height
  • list-style
  • list-style-image
  • list-style-position
  • list-style-type
  • margin
  • margin-bottom
  • margin-left
  • margin-right
  • margin-top
  • marks
  • max-height
  • max-width
  • min-height
  • min-width
  • mix-blend-mode
  • object-fit
  • opacity
  • order
  • orphans
  • outline
  • outline-color
  • outline-offset
  • outline-style
  • outline-width
  • overflow
  • overflow-x
  • overflow-y
  • padding
  • padding-block
  • padding-block-end
  • padding-block-start
  • padding-bottom
  • padding-inline
  • padding-inline-end
  • padding-inline-start
  • padding-left
  • padding-right
  • padding-top
  • page-break-after
  • page-break-before
  • page-break-inside
  • perspective
  • perspective-origin
  • place-content
  • pointer-events
  • position
  • quotes
  • resize
  • right
  • scroll-behavior
  • tab-size
  • table-layout
  • text-align
  • text-align-last
  • text-decoration
  • text-decoration-color
  • text-decoration-line
  • text-decoration-skip-ink
  • text-decoration-style
  • text-emphasis
  • text-emphasis-color
  • text-emphasis-position
  • text-emphasis-style
  • text-fill-color
  • text-indent
  • text-orientation
  • text-overflow
  • text-shadow
  • text-stroke
  • text-stroke-color
  • text-stroke-width
  • text-transform
  • top
  • transform
  • transform-origin
  • transform-style
  • transition
  • transition-delay
  • transition-duration
  • transition-property
  • transition-timing-function
  • unicode-bidi
  • user-select
  • vertical-align
  • visibility
  • white-space
  • widows
  • width
  • word-break
  • word-spacing
  • word-wrap
  • writing-mode
  • z-index
  • zoom

Источник

CSS filter Property

Tip: More «Try it Yourself» examples below.

Definition and Usage

The filter property defines visual effects (like blur and saturation) to an element (often ).

Default value: none
Inherited: no
Animatable: yes. Read about animatable Try it
Version: CSS3
JavaScript syntax: object.style.filter=»grayscale(100%)» Try it

Browser Support

The numbers in the table specify the first browser version that fully supports the property.

Numbers followed by -webkit- specify the first version that worked with a prefix.

CSS Syntax

filter: none | blur() | brightness() | contrast() | drop-shadow() | grayscale() | hue-rotate() | invert() | opacity() | saturate() | sepia() | url();

Tip: To use multiple filters, separate each filter with a space (See «More Examples» below).

Filter Functions

Note: The filters that use percentage values (i.e. 75%), also accept the value as decimal (i.e. 0.75).

Filter Description Demo
none Default value. Specifies no effects Demo ❯
blur(px) Applies a blur effect to the image. A larger value will create more blur.

Possible values:
h-shadow — Required. Specifies a pixel value for the horizontal shadow. Negative values place the shadow to the left of the image.

v-shadow — Required. Specifies a pixel value for the vertical shadow. Negative values place the shadow above the image.

blur — Optional. This is the third value, and must be in pixels. Adds a blur effect to the shadow. A larger value will create more blur (the shadow becomes bigger and lighter). Negative values are not allowed. If no value is specified, 0 is used (the shadow’s edge is sharp).

spread — Optional. This is the fourth value, and must be in pixels. Positive values will cause the shadow to expand and grow bigger, and negative values will cause the shadow to shrink. If not specified, it will be 0 (the shadow will be the same size as the element).
Note: Chrome, Safari and Opera, and maybe other browsers, do not support this 4th length; it will not render if added.

color — Optional. Adds a color to the shadow. If not specified, the color depends on the browser (often black).

An example of creating a red shadow, which is 8px big both horizontally and vertically, with a blur effect of 10px:

filter: drop-shadow(8px 8px 10px red);

0% (0) is default and represents the original image.
100% will make the image completely gray (used for black and white images).

0% (0) is default and represents the original image.
100% will make the image completely inverted.

0% is completely transparent.
100% (1) is default and represents the original image (no transparency).

0% (0) will make the image completely un-saturated.
100% is default and represents the original image.
Values over 100% provides super-saturated results.

0% (0) is default and represents the original image.
100% will make the image completely sepia.

More Examples

Blur Example

Apply a blur effect to the image:

Источник

How to Convert an Image into a Grayscale Image With CSS

There are lots of ways to make your image grayscale with the help of CSS. In this snippet, we are going to learn how to convert a colored image into grayscale using CSS properties.

Solution with the CSS filter property

In the example below, we put our image in the tag and then, use the «grayscale» value of the filter property.

Example of creating a grayscale image with the filter property:

html> html> head> title>Title of the document title> style> img < -webkit-filter: grayscale(100%); filter: grayscale(100%); > style> head> body> h2>Convert an image into grayscale using HTML/CSS h2> img src="/uploads/media/default/0001/01/b408569013c0bb32b2afb0f0d45e93e982347951.jpeg" width="400" height="300" alt="tree"/> body> html>

Result

tree

Convert an image into grayscale using HTML/CSS

Now, let’s see another example.

Example of creating a grayscale image with a hovering effect:

html> html> head> title>Title of the document title> style> img < -webkit-filter: grayscale(1); filter: grayscale(1); > img:hover < -webkit-filter: grayscale(0); filter: none; > h1 < color: green; > style> head> body> h2>Convert an image into grayscale using HTML/CSS h2> img src=" /uploads/media/default/0001/01/b408569013c0bb32b2afb0f0d45e93e982347951.jpeg" width="400" height="300" alt="tree"/> body> html>

Solution with the CSS background-blend-mode property

A new way to make the image grayscale is available on modern browsers. The background-blend-mode allows you to get some interesting effects like grayscale conversion. Set this property to its «luminosity» value on a white background.

Example of creating a grayscale image using the background-blend-mode property:

html> html> head> title>Title of the document title> style> .example < width: 400px; height: 300px; background: url("/uploads/media/default/0001/01/4982c4f43023330a662b9baed5a407e391ae6161.jpeg"), #fff; background-size: cover; > .example:hover < background-blend-mode: luminosity; > style> head> body> h2>Convert an image into grayscale using HTML/CSS h2> div class="example"> div> body> html>

You can animate the effect setting 3 layers. The first one is the image, and the second is the white-black gradient. On the white part of the gradient, you get the same effect as before. On the black part of the gradient, you are blending the image over itself, and the result is the unmodified image.

Example of creating a grayscale image using a linear-gradient:

html> html> head> title>Title of the document title> style> div < width: 450px; height: 400px; > .example < background: url("/uploads/media/default/0001/01/4982c4f43023330a662b9baed5a407e391ae6161.jpeg"), linear-gradient(0deg, white 33%, black 66%), url("/uploads/media/default/0001/01/4982c4f43023330a662b9baed5a407e391ae6161.jpeg"); background-position: 0px 0px, 0px 0%, 0px 0px; background-size: cover, 100% 300%, cover; background-blend-mode: luminosity, multiply; transition: all 1.5s; > .example:hover < background-position: 0px 0px, 0px 70%, 0px 0px; > style> head> body> h2>Convert an image into grayscale using HTML/CSS h2> div class="example"> div> body> html>

Источник

Читайте также:  Только непосредственные потомки css
Оцените статью