- Мета-тег цвета темы цветовой полосы Chrome Mobile не работает
- 5 ответов
- Meta Theme Color and Trickery
- Заметки Веб-разработчика
- Смена цвета вкладки открытого сайта на телефоне и Кастомизация ползунка прокрутки сайта
- Как сменить цвет вкладки открытого сайта в мобильных браузерах?
- Как изменить стили ползунка прокрутки всего сайта?
Мета-тег цвета темы цветовой полосы Chrome Mobile не работает
Я пытаюсь реализовать метатег theme-color , но не вижу, чтобы он работал на моем смартфоне Motorola с Chrome и Android Lollipop.
Я начал с тега theme-color , затем написал другие теги, но безуспешно.
Эта веб-страница работает по HTTPS с недопустимым сертификатом (это инструмент интрасети), но я не думаю, что это повлияет на эту функцию, верно?
5 ответов
Из моего опыта тестирования требуется действующий сертификат.
У меня была та же проблема, что и при тестировании на моем локальном хосте (т. Е. Цвет фона адресной строки не изменился на мобильном устройстве), но как только я перешел на производство (т.е. производство имеет действительную сертификацию), я смог просмотреть изменения, отраженные устройства для тестирования Android.
Используемые устройства Android: OnePlus 3T, Huawei, старый телефон Samsung. Все были положительные результаты.
В моем случае это была тема, которую использовал мой телефон. Мета-тег theme-color не работает в темной теме Android (на момент написания этой статьи я использовал Android 10). Переключитесь на светлую тему в Chrome, и вы убедитесь, что она работает. 🙂
Chrome требует, чтобы у вас был действующий сертификат для работы цвета панели темы
Пожалуйста, проверьте тему своего браузера? Может там включен тёмный режим!
Источник
Meta Theme Color and Trickery
Take your JavaScript to the next level at Frontend Masters.
Starting with Version 15, Safari supports the theme-color tag both on macOS and iOS. That’s exciting news because now the first desktop browser supports this tag and it also supports the media attribute and the prefers-color-scheme media feature.
I never really took much note of the theme-color meta tag, but now is a good time to learn about its features and limitations and try to discover some interesting use cases.
Heads up! Safari removed support for the theme-color meta tag in Safari Technology Preview (127). That was only temporary, starting with release 128 it supports it again.
Features and limitations
Here’s how I’ve been using the theme-color meta tag for the past few years: just a good ‘ol hex code for the content attribute.
According to tests I made earlier this year, this works in Chrome, Brave and Samsung Internet on Android, installed PWAs in Chrome and now also in Safari Technology Preview.
CSS color support
One of the first questions that came to my mind was “Can we use color keywords, hsl() , rgb() , too?” According to the HTML spec, the value of the attribute can be any CSS color. I’ve created this theme-color testing CodePen to verify that.
All supported browsers also support hsl() and rgb() . This is awesome because it allows us to do some pretty cool stuff with JavaScript. We’ll talk about that later, but first let’s look at some limitations.
HEX codes, rbg() , hsl() and keywords are well and consistently supported, but colors that include transparency: not so much. Actually, they are supported in most browsers, but the results aren’t very consistent and sometimes unexpected.
transparent is a CSS color and used in the theme-color meta tag most browsers do what you’d expect. All regular mobile browsers don’t change color and display the default tab bar, but Safari on macOS and the Chrome Canary PWA on macOS turn the tab bar black. The PWA on Android falls back to theme-color defined in the manifest.json , which we’ll talk about in a bit.
All browsers interpret hsla() and rgba() , but they set the alpha value to 1. The only exception is Safari on macOS; it interprets the transparency, but it seems like the transparent color has a black baseline. This has the effect that the light orange color looks like dark orange.
New color functions
Safari 15 is the first browser to support lab() , lch() , and hwb() color functions. These functions work if you use them in CSS, but not if you use them in the theme-color meta tag.
All three declarations work fine in Safari 15:
If you use any of the new color functions in the theme-color meta tag, Safari doesn’t interpret them and falls back to its own algorithm of picking the color. It’s likely that Safari uses the background color of your for the theme-color , which means that you might get the expected result without defining the theme-color explicitly.
Please be aware that at the time of writing Safari 15 is the only browser to support these new colors functions.
If CSS colors are supported, currentColor should work, too, right? No, unfortunately not in any browser. It’s probably an uncommon use case, but I would expect that we can set the theme-color to the current color of the or element.
I found a ticket in the WebKit bug tracker titled “ should also support CSS currentcolor .” Support might change in the future, if someone picks the ticket up.
When I was testing CSS color keywords, I used the color red and it didn’t work. First, I thought that keywords weren’t supported, but blue , hotpink , and green worked fine. As is turns out, there’s a narrow range of colors that Safari doesn’t support, colors that would get in the way of using the interface. red doesn’t work because it’s visually too close to the background color of the close button in the tab bar. This limitation is specific to Safari, in all other supported browsers any color seem to work fine.
I don’t know enough about the internals of browsers and custom properties and if it’s even possible to access custom properties in the , but I tried it anyway. Unfortunately, it didn’t work in any browser.
That’s pretty much everything I wanted to know about basic support of the theme-color meta tag. Next, let’s see how to and how not to implement dark mode for the tab bar.
Safari 15 is the first desktop browser to support the media attribute and the prefers-color-scheme media feature on theme-color meta tags. Starting with version 93, Chrome supports it too, but only for installed progressive web apps.
According to the web app manifest page on web.dev, if you define multiple theme-color meta tags, browsers pick the first tag that matches.
I was eager to find out what happens in browsers that don’t support the media attribute. I’ve created a demo page for testing dark mode that includes the meta tags above and also allows you to install the site as a PWA. The webmanifest.json includes another color definition for the theme-color.
Here’s how supported browsers display the tab bar in light mode. It doesn’t matter if a browser supports the media attribute or not, it will interpret the first meta tag regardless.
Here’s how the tab bar on the same page looks like in dark mode. These results are more interesting because they vary a bit. The Canary PWA and Safari support and show the dark color. All mobile browsers use their default dark tab bar styling, except for Samsung Internet, which uses the light styling because it doesn’t support the prefers-color-scheme media feature. (TIL : This should change in the near future.)
I did one last test. I wanted to see what happens if I only define a theme color for dark mode, but access the page in light mode.
These results surprised me the most because I expected all mobile browsers to ignore the media attribute and just use the dark color in the meta tag regardless, but ordinary Chrome Canary completely ignores the whole meta tag, even though it doesn’t support the media attribute. As expected, both Canary PWAs fall back to the color defined in the manifest file.
The other interesting thing is that Safari displays a theme-color even though I haven’t defined one for light mode. That’s because Safari will pick a color on its own, if you don’t provide a theme-color . In this case, it uses the background color of the page, but it also might use the background color of the element, for example.
If you want to define a theme color for light and dark mode, your best bet is to define both colors and use the first meta tag as a fallback for browsers that don’t support the media feature.
Safari has proven that theme-color works great on desktop browsers, too. I’m sure that designers and developers will find many creative ways to use this meta tag, especially considering that the value can be changed via JavaScript. I’ve collected and created some interesting demos for your inspiration.
Demos and use cases
poolsuite.net provides different themes for the site and changes the theme-color accordingly.
Max Böck also changes the theme-color on his website when you change the theme.
Most websites don’t provide custom themes, but you can still give your pages that certain something. Dave uses different key colors in his blog posts for links and icons, and now also in the tab bar.
If you’re using gradients on your page, you can highlight your styling by making the gradient span the whole browser. The theme-color meta tag doesn’t support gradients, but you can use the same color for the meta tag and the start color of the gradient of you page’s background.
I built this proof of concept of a form that changes theme-color on form validation. It starts with a blue tab bar which turns red if the submitted data is invalid or green if it’s valid.
I’m not saying that you should, but you could put your site in 💃 Disco Mode 🕺 by combining setInterval and hsl() colors.
Stuart had a great idea, he suggested changing theme color on scroll. I built this quick prototype, again using hsl() colors.
Please only do this if it doesn’t affect performance negatively.
Max built a demo in which he changes the theme-color according to the background color of the current section in the viewport using Intersection Observer.
Another interesting idea is to extract the dominant or average color from your header images automatically and use it as the theme-color .
That is just a handful of ideas, but I already like where this is going and I’m sure that you’ll come up with even more creatives ways of using the theme-color meta tag.
Источник
Заметки Веб-разработчика
Полезная информация для исполнителей и заказчиков
Смена цвета вкладки открытого сайта на телефоне и Кастомизация ползунка прокрутки сайта
Как обычно, сразу к делу.
Как сменить цвет вкладки открытого сайта в мобильных браузерах?
Все максимально просто. В теге head размещайте приведенные внизу meta теги:
Эти meta теги отвечают за изменение цвета вкладки сайта на мобильных браузерах в android и ios системах. В атрибутах content необходимо указать нужный вам цвет.
На изображении внизу видно пример того, как были использованы эти meta теги на моем сайте по сравнению со стандартным цветом вкладки в поисковике гугл.
В моем случае я использовал цвет #2b2c2d вставляя его в атрибут content.
Как изменить стили ползунка прокрутки всего сайта?
Здесь уже немного интереснее. Сейчас мы сделаем штуку, которая изображена на фото ниже:
Мы кастомизировали стандартный вид скрола на сайте, а именно: сменили цвет, форму и фон скролбара с помощью специальных псевдоелементов. Для для того, чтобы сделать так же, скопируйте css код ниже:
Вы можете изменять скрол на сайте как вам будет угодно. У вас есть возможность менять размеры скрола, добавлять ему тень, высоту ползунка, кнопки и даже просто убирать его с экрана с помощью display: none. Естественно, если вам необходимо кастомизировать только определенный скролбар на сайте, задайте эти псевдоелементы именно ему, а не глобально как это было сделано выше.
Примечание. К сожалению только webkit браузеры как Chrome, Opera и Safari работают с такими псевдоелементами. На браузерах Firefox, IE и Edge они не поддерживаются.
Источник