Mask for background css

Как использовать маски в CSS

От автора: когда вы обрезаете элемент, используя свойство clip-path, обрезанная область становится невидимой. Если вместо этого вы хотите сделать часть изображения непрозрачной или применить к ней какой-либо другой эффект, вам необходимо использовать маску. В этом посте объясняется, как применять свойство CSS mask-image, которое позволяет указать изображение для использования в качестве слоя маски. Это дает вам три варианта. Вы можете использовать в качестве маски файл изображения, SVG или градиент.

Совместимость с браузерами

Большинство браузеров только частично поддерживают стандартное свойство маскировки CSS. Вам нужно будет использовать префикс -webkit- в дополнение к стандартному свойству, чтобы достичь наилучшей совместимости с браузером. Для получения полной информации о поддержке браузерами см. Могу ли я использовать маски CSS?

Хотя поддержка браузерами с помощью свойства prefixed хороша, при использовании маскирования для отображения текста поверх изображения позаботьтесь о том, что произойдет, если маскирование недоступно. Перед добавлением замаскированной версии, возможно, стоит использовать запросы функций для обнаружения поддержки mask-image или -webkit-mask-image и предоставления удобочитаемого отката.

Frontend-разработчик

Курс «Frontend-разработчик»

— Научитесь верстать сайты для всех типов устройств.

— Сможете использовать JavaScript для работы в браузере.

— 77 часов теории, 346 часов практики.

— Выполните 5 масштабных проектов для портфолио.

— Помощь с поиском работы или стажировки.

Курс веб-разработчик с нуля

Курс «веб-разработчик с нуля»

— Научитесь программировать на JavaScript и PHP.

— Сможете создавать сайты и веб-приложения.

— Сможете уверенно работать и с фронтендом, и с бэкендом веб-сервисов.

— Выполните 9 масштабных проектов для портфолио

— Помощь с поиском работы или стажировки.

PHP-разработчик с нуля

Курс «PHP-разработчик с нуля»

— Научитесь создавать сайты и веб-приложения на языке PHP.

— Изучите актуальные фреймворки Laravel, Simfony и Yii2.

— 78 часов теории и 361 час практики.

— Вы создадите 5 масштабных проектов для портфолио.

— Помощь с поиском работы или стажировки.

Маскировка изображением

Свойство mask-image работает аналогичным образом с background-image. Используйте значение url() для передачи изображения. Изображение маски должно иметь прозрачную или полупрозрачную область.

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

В этом примере я также использую свойство mask-size со значением cover. Это свойство работает так же, как background-size. Вы можете использовать ключевые слова cover и / или contain, вы можете задать размер фона, используя любую допустимую единицу длины или проценты.

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

Маскирование с помощью SVG

Вместо того, чтобы использовать в качестве маски файл изображения, вы можете применить SVG. Этого можно добиться несколькими способами. Первый – разместить элемент внутри SVG и ссылаться на идентификатор этого элемента в свойстве mask-image.

Источник

mask

The mask CSS shorthand property hides an element (partially or fully) by masking or clipping the image at specific points.

Note: As well as the properties listed below, the mask shorthand also resets mask-border to its initial value. It is therefore recommended to use the mask shorthand rather than other shorthands or the individual properties to override any mask settings earlier in the cascade. This will ensure that mask-border has also been reset to allow the new styles to take effect.

Constituent properties

This property is a shorthand for the following CSS properties:

Syntax

/* Keyword values */ mask: none; /* Image values */ mask: url(mask.png); /* Pixel image used as mask */ mask: url(masks.svg#star); /* Element within SVG graphic used as mask */ /* Combined values */ mask: url(masks.svg#star) luminance; /* Element within SVG graphic used as luminance mask */ mask: url(masks.svg#star) 40px 20px; /* Element within SVG graphic used as mask positioned 40px from the top and 20px from the left */ mask: url(masks.svg#star) 0 0/50px 50px; /* Element within SVG graphic used as mask with a width and height of 50px */ mask: url(masks.svg#star) repeat-x; /* Element within SVG graphic used as horizontally repeated mask */ mask: url(masks.svg#star) stroke-box; /* Element within SVG graphic used as mask extending to the box enclosed by the stroke */ mask: url(masks.svg#star) exclude; /* Element within SVG graphic used as mask and combined with background using non-overlapping parts */ /* Global values */ mask: inherit; mask: initial; mask: revert; mask: revert-layer; mask: unset; /* Multiple masks */ mask: url(masks.svg#star) left / 16px repeat-y, /* Element within SVG graphic is used as a mask on the left-hand side with a width of 16px */ url(masks.svg#circle) right / 16px repeat-y; /* Element within SVG graphic is used as a mask on the right-hand side with a width of 16px */ 

Values

Sets the mask image source. See mask-image .

Sets the masking mode of the mask image. See mask-mode .

Sets the position of the mask image. See mask-position .

Sets the size of the mask image. See mask-size .

Sets the repetition of the mask image. See mask-repeat .

If only one value is given, it sets both mask-origin and mask-clip . If two values are present, then the first sets mask-origin and the second sets mask-clip .

Sets the area that is affected by the mask image. See mask-clip .

Sets the compositing operation used on the current mask layer. See mask-composite .

Formal definition

  • mask-image : none
  • mask-mode : match-source
  • mask-repeat : repeat
  • mask-position : center
  • mask-clip : border-box
  • mask-origin : border-box
  • mask-size : auto
  • mask-composite : add
  • mask-position : refer to size of mask painting area minus size of mask layer image (see the text for background-position )
  • mask-image : as specified, but with url() values made absolute
  • mask-mode : as specified
  • mask-repeat : Consists of two keywords, one per dimension
  • mask-position : Consists of two keywords representing the origin and two offsets from that origin, each given as an absolute length (if given a ), otherwise as a percentage.
  • mask-clip : as specified
  • mask-origin : as specified
  • mask-size : as specified, but with relative lengths converted into absolute lengths
  • mask-composite : as specified
  • mask-image : discrete
  • mask-mode : discrete
  • mask-repeat : discrete
  • mask-position : a repeatable list of
  • mask-clip : discrete
  • mask-origin : discrete
  • mask-size : a repeatable list of
  • mask-composite : discrete

Formal syntax

mask =
#

=
||
[ / ]? ||
||
||
[ | no-clip ] ||
||

=
none |
|

=
[ left | center | right ] || [ top | center | bottom ] |
[ left | center | right | ] [ top | center | bottom | ]? |
[ [ left | right ] ] && [ [ top | bottom ] ]

=
[ | auto ] |
cover |
contain

=
repeat-x |
repeat-y |
[ repeat | space | round | no-repeat ]

=
|
fill-box |
stroke-box |
view-box

=
add |
subtract |
intersect |
exclude

=
alpha |
luminance |
match-source

=
|

=

=
|

=
|
margin-box

=
url( * ) |
src( * )

=
border-box |
padding-box |
content-box

Examples

Masking an image

.target  mask: url(#c1) luminance; > .anothertarget  mask: url(resources.svg#c1) 50px 30px/10px 10px repeat-x exclude; > 

Specifications

Browser compatibility

BCD tables only load in the browser

See also

Found a content problem with this page?

This page was last modified on Jul 7, 2023 by MDN contributors.

Your blueprint for a better internet.

MDN

Support

Our communities

Developers

Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.

Источник

Читайте также:  Page object pattern python selenium
Оцените статью