How to blur background css
How to blur background css
Search
Quick Links
Components
Globals
Projects
Feeling lost? Feel free to get in touch!
How to create clipped, blurred background images in CSS
In this tutorial, we’ll take a look at how to apply blur effects to images using CSS filters, and how to confine these effects to specific image areas.
By Sebastiano Guerriero Follow author on Twitter
Let’s do this! #
I’ve put together a video tutorial that explains in details how to create the blur effect.
The component we build in this tutorial is based on the CodyHouse framework.
👋 First time you hear about the CodyHouse Framework?
The idea behind the effect is the following: we need to duplicate the image of the team member, then we have to apply the CSS blur filter to this copy and a mask so that only part of the image is visible.
By targeting each team member card using their IDs, we can set a different image for each member.
When you apply the blur filter, you’ll notice the edges are semitransparent. We can fix this issue by creating an additional copy of the image using the ::after pseudo-element, and by increasing the size of the ::before element with the scale transformation:
Optionally, you can target browsers that support the backdrop-filter property, and use this alternative technique to create the same effect with just one line of code. Unfortunately, support is not great at the moment, so we decided to include both methods.
Как сделать размытие фона в CSS с помощью одной строки кода
Дата публикации: 2020-03-26
От автора: фоновые размытые изображения — это круто. Это неоспоримый факт. В каждом пользовательском интерфейсе должно быть не менее десяти фоновых размытых изображений (желательно наложенных друг на друга), и каждый интерфейс, созданный с самого зарождения всемирной паутины, который не содержит фоновых размытых изображений, должен быть переработан в первую очередь. Это правда. Разработчики любят, когда вы показываете им дизайн с размытым фоном. А это ложь.
Потому что размытия фона практически невозможно реализовать в веб-приложениях, поэтому дизайнеры чувствуют себя разочарованными, обманутыми и совершенно бесполезными. Но сегодня все меняется. Ну, на самом деле это изменилось еще в 2018 году или что-то около того, это только я что нашел страницу MDN, но вы поняли суть.
Итак, вот как создать размытие фона с помощью свойства CSS backdrop-filter.
Практический курс по верстке адаптивного сайта с нуля!
Изучите курс и узнайте, как верстать современные сайты на HTML5 и CSS3
Вот и все. Если вы все же хотите прочитать больше, вот немного подробнее…
Что такое backdrop-filter?
Согласно MDN: «Свойство backdrop-filterCSS позволяет применять графические эффекты, такие как размытие или смещение цвета, к области позади элемента. Поскольку это относится ко всему, что находится за элементом, чтобы увидеть эффект, вы должны сделать элемент или его фон хотя бы частично прозрачным».
Если вы ума не приложите, что они имели в виду в последнем предложении, то в основном они говорят, что это работает точно так же, как и в выбранном вами инструменте дизайна (Figma, Sketch, Adobe XD, Framer, что-нибудь еще).
Все, что скрывается за размытием… становится размытым.
Давайте возьмем простой пример
Практический курс по верстке адаптивного сайта с нуля!
Изучите курс и узнайте, как верстать современные сайты на HTML5 и CSS3
Если вы хотите, чтобы размытие имело цвет, вам нужно добавить свойство background со значением rgba. Убедитесь, что альфа-канал (непрозрачность) меньше 1, чтобы мы могли видеть сквозь цвет.
Затем мы добавим магическое свойство CSS backdrop-filter и присвоим ему значение blur(8px). Подсказка: увеличьте / уменьшите px, чтобы увеличить / уменьшить размытие.
На полном серьезе, это очень круто.
Добавление нескольких фильтров
Если вы хотите добавить к элементу несколько свойств backdrop-filter, просто разделите их пробелами. Будьте осторожны; они могут не сочетаться вместе. И да, через точку с запятой после моей предыдущей статьи в Medium. Что происходит.
Вот мой пример на Codepen с анимацией и кнопкой для переключения класса, содержащего несколько свойств backdrop-filter:
Очевидно, вы можете применить к этому изобретательность. Это было экспериментальное свойство некоторое время, поэтому обязательно проверьте совместимость браузеров. На момент написания этой статьи MDN говорит, что все основные браузеры, за исключением Internet Explorer, Firefox для Android и Samsung Internet, используют его.
Героическим людям, которые сделали это возможным, искренняя благодарность от меня. Вы позволили, чтобы наши снимки на Dribbble имели гораздо больше шансов увидеть свет.
Надеюсь, что это базовое описание использования backdrop-filter для создания размытия фона поможет, по крайней мере, одному человеку. Пожалуйста, не стесняйтесь оставлять свои комментарии. Спасибо за чтение. Приятно провести время!
Автор: Andrew Nicholl
Редакция: Команда webformyself.
Практический курс по верстке адаптивного сайта с нуля!
Изучите курс и узнайте, как верстать современные сайты на HTML5 и CSS3
Верстка. Быстрый старт
Практический курс по верстке адаптивного сайта с нуля!
How to make a background blur in CSS with one line of code
Background blurs are cool. This is an undisputed fact. Every single user interface should have at least ten background blurs in them (preferably stacked on top of each other), and every interface made since the creation of the world wide web without background blurs should be flagged as high priority technical debt. This is the Truth. Developers love when you show them design proofs with background blurs. This is false.
That’s because background blurs have been basically impossible to implement on web applications, making designers feel frustrated, lied to, and utterly useless as human beings. But that all changes today. Well, it actually changed in 2018 or something and I just found the MDN page, but you get the point.
So, here’s how to create a background blur using the backdrop-filter CSS property.
If you insist on reading the rest of the article, here’s a little more detail…
What is backdrop-filter?
According to MDN, “The backdrop-filter CSS property lets you apply graphical effects such as blurring or color shifting to the area behind an element. Because it applies to everything behind the element, to see the effect you must make the element or its background at least partially transparent.”
In case you smashed your eyeballs into a pair of scissors halfway through the first sentence, they’re basically saying it works in dev exactly the same as it works in your design tool of choice (Figma, Sketch, Adobe XD, Framer, anything else that will help with SEO of this article).
Whatever is behind the blur…get’s blurry.
Let’s make a simple example
Start by creating a
Now let’s add the blur. We’re going to quietly sneak inside that
This is forty-fifth round Google interview type shit right here. Let’s finish changing hearts and minds.
If you want the blur to have a color, you’ll need to add the background property with an rgba value. Make sure that the alpha (opacity) is less than 1, so we can see through the color.
You should now be staring directly at the pinnacle of human ingenuity and invention. Four pineapples with half of them blurred out. In all seriousness, it’s very cool.
Adding Multiple Filters
If you want to add multiple backdrop-filter properties to an element, just separate them with spaces. Be careful though; they may not play nicely together. Yeah, dropping semicolons in my first Medium article. What’s up.
Here is my Codepen example complete with pointless animation and a button to toggle the class containing multiple backdrop-filter properties:
Clearly, you can get pretty inventive with this. It’s been experimental for a while, so make sure to check browser compatibility and all that important stuff. As of writing this, MDN says every major browser except for Internet Explorer, Firefox for Android, and Samsung Internet use it, so write some fallbacks for those.
To the heroes who made this happen, I sincerely thank you. You’ve made our Dribbble shots have that much more of a chance of seeing the light of day.
Hope this basic rundown of using backdrop-filter to create a background blur helps at least one human. Please feel free to comment with any thoughts, suggestions, or vitriolic hate. I got myself a Twitter, Dribbble, and you can follow me on Medium in case I ever decide to do this again.
Thank you for reading. Have a beautiful time!
Create OS-style backgrounds with backdrop-filter
Blurring and color shifting behind an element.
Translucence, blurring, and other effects are useful ways of creating depth while keeping the context of the background content. They support a host of use cases such as frosted glass, video overlays, translucent navigation headers, inappropriate image censoring, image loading, and so on. You may recognize these effects from two popular operating systems: Windows 10 and iOS. An example of a frosted glass effect. Source.
Basics #
Caution
CSS backdrop-filter applies one or more effects to an element that is translucent or transparent. To understand that, consider the images below.
No foreground transparency
You can combine filters for rich and clever effects, or use just one filter for more subtle or precise effects. You can even combine them with SVG filters.
Feature detection and fallback #
Examples #
Design techniques and styles previously reserved for operating systems are now performant and achievable with a single CSS declaration. Let’s look at some examples.
Single filter #
Try this example for yourself in CodePen.
Multiple filters #
Sometimes you’ll need multiple filters to achieve the desired effect. To do this, provide a list of filters separated by a space. For example:
In the following example, each of the four panes has a different combination of backdrop filters while the same set of shapes are animated behind them. Try this example for yourself in CodePen.
Overlays #
This example shows how to blur a semi-transparent background to make text readable while stylistically blending with a page’s background.
Try this example for yourself.
Text contrast on dynamic backgrounds #
As stated earlier, backdrop-filter allows performant effects that would be difficult or impossible on the web. An example of this is changing a background in response to an animation. In this example, backdrop-filter maintains the high contrast between the text and its background in spite of what’s going on behind the text. It starts with the default background color darkslategray and uses backdrop-filter to invert the colors after the transformation.
Try this example from Chen Hui Jing in Codrops.
Conclusion #
More than 560 of you have upvoted the Chromium bug over the past few years, clearly marking this as a long awaited CSS feature. Chrome’s release of backdrop-filter in version 76 brings the web a step closer to truly OS-like UI presentation.
Продвинутые CSS фильтры
Перевод статьи advanced css filters, авторства Vincent De Oliveira, найденная мною в последнем дайджесте.
Я не смог коротко перевести на русский backdrop и background, сохранив смысловую разницу между ними, поэтому поясню сейчас:
backdrop — то, что находится за элементом, и может быть видно через него, обрезано по его рамке;
background — тоже фон, но является частью элемента, к нему и относится свойство background.
Вернемся в 2011 год, браузеры начали вводить CSS фильтры из спецификаций. В это время поддерживались в основном SVG фильтры, а Firefox был единственным браузером, который мог применить их к HTML контенту (в основном, ничего не изменилось).
CSS фильтры такие как blur(), contrast() или grayscale() — отличное дополнение к CSS, несмотря на то, что SVG может позволить сделать восхитительные вещи. Больше узнать о них вы можете на множестве ресурсов.
Сегодня я хочу пойти чуть дальше, показав новые возможности CSS.
backdrop-filter
В первую очередь — это backdrop-filter свойство, определенное в Filter Effect Level 2. Оно позволяет применять фильтры к фону(backdrop) элемента, а не к его фону(background).
Я был настроен скептически, но я начал играться в WebKit nightlies в феврале, и изменил свое мнение — это очень круто. Каждый согласится со мной, что подтверждается моим Vine (сервис, похожий на Сoub — прим. переводчика) постом, который собрал более 20 тысяч просмотров за 48 часов.
В июне, Apple анонсировала на WWDC, что эти свойства будут доступны в Safari 9. Это хорошая новость. Самое время проверить, (автор использует бету iOS 9 и Safari 9).
С этим свойством вы можете получить эфекты, которых добиться было тяжело. Самое банальное — размытие как в iOS:
Каждый элемент за header`ом размыт на 5px. Это так просто.
Живой пример на JSBin (только Safari 9).
В демо, я использовал для того, чтобы применить backdrop-filter вместе с небольшими корректировками (background-color и позиционирование), чтобы сохранить читаемость header`а в неподдерживаемых браузерах.
backdrop-filter может повысить читаемость текста, наложенного поверх изображения:
Живой пример на JSBin (только Safari 9).
Комбинируя несколько фильтров, вы можете сделать простые графические эффекты, близкие к тем, которые предлагает CSS blend-modes:
Живой пример на JSBin (только Safari 9).
filter()
Иногда, надо наложить фильтр ни на элемент, ни на фон(backdrop). Вы просто хотите применить его к фону(background), но свойства background-filter нет. Вот тут может пригодиться функция filter(), не следует путать со свойство filter. Функция принимает два параметра: изображение и фильтр, возвращает новое изображение. Это изображение можно использовать с любым CSS свойством, поддерживающим изображения. Как то так:
В результате, теперь можно применять фильтры для изображений, перед использование в качестве фона. Вы можете подумать, что она — вариация background-filter (или background-opacity, background-blur), но она намного мощнее.
Живой пример на JSBin (только Safari 9).
Хорошая новость в том, что даже без упоминания Apple, она доступна в Safari 9.
Я с нетерпением жду, когда в браузерах введут эти фичи. SVG тоже может это делать, но такие же крутые эфекты можно легко сделать с CSS. С прошлого года, много споров вокруг CSS были сфокусированы на архитектуре, методологии, инструментах. Хорошо помнить о том, что CSS так же и о графическом дизайне (вместе с SVG).
OK, сейчас поддержка минимальна, но это станет возможным на миллионах iPhone`ов и iPad`ов до конца года.