Css dark background color

Dark Mode in CSS

With the introduction of dark mode in macOS, Safari Technology Preview 68 has released a new feature called prefers-color-scheme which lets us detect whether the user has dark mode enabled with a media query. Safari Technology Preview 71 also has supported-color-schemes , which… well, I couldn’t exactly tell you what that does. The media query is like this:

@media (prefers-color-scheme: dark)

It may not be supported everywhere just yet, but it’s a great progressive enhancement, it’s implemented in a good/smart/standards-compliant way, so it’s safe to start using. Just like prefers-reduced-motion!

It’s not just setting dark backgrounds with light text…

Recently Mark Otto described how we can start using prefers-color-scheme today in order to create themes that dynamically adjust to the new user setting. And the neat thing about this post is that Mark sort of frames it as an accessibility issue and shows how he uses it on his own website to adjust images so that they’re not too bright for the user:

@media (prefers-color-scheme: dark) < img < opacity: .75; transition: opacity .5s ease-in-out; >img:hover < opacity: 1; >>

In the code above, Mark detects whether the user has dark mode enabled with the media query and then makes the images darker so that they match a dark background.

Читайте также:  Injecting javascript in url

CSS Custom Properties may be useful

This reminds me of an excellent post by Marcin Wichary where he explores a similar technique and goes one step further by adding all sorts of filters to make sure they have a much higher contrast.

It doesn’t mean you have to give up your brand

Andy Clarke also wrote up some thoughts about how to take this fancy new CSS feature and how we might apply a dark theme across our website. He describes how to pick colors so our light/dark themes are consistent in terms of branding and how we might want to use a lighter font-weight for darker backgrounds. He writes:

Designing for dark mode shouldn’t stop with choosing darker colours. You should also consider altering typography styles to maintain readability for people who use dark mode. Light text against dark backgrounds appears higher in contrast than when the same colours are used in reverse, so to make your dark mode designs easier to read you’ll need to add more white/dark space to your text. If your fonts offer a lighter weight, using that for your dark mode design will open up the letterforms and make them appear further apart…

What was that? It sure sounded like the joyous applause of typography nerds and designers everywhere!

It’s about inclusive design

Charles Reynolds-Talbot writes about his friend Molly, who has trouble with high-contrast white backgrounds with black text:

Assuming a style switcher is the solution to this problem, it’s nothing new. It’s just something that isn’t trendy anymore. But this shouldn’t be about fashion, this is about inclusive design for all. Solving this problem for Molly will actually solve problems for other people too. A dark mode will be better for people who suffer from migraines, have a hangover or are just browsing the web in bed at night with the light off. Designing for the few, makes things better for the many.

Remember you can reverse it and go dark by default but change to a light theme if a user specifically wants it:

body < background-color: black; color: white; >@media screen and (prefers-color-scheme: light) < body < background-color: white; color: black; >>

Источник

Как добавить темную тему на свой сайт с помощью CSS и JavaScript

Как добавить темную тему на свой сайт с помощью CSS и JavaScript

С помощью CSS очень легко добавить темную тему для существующих веб-сайтов. В этом руководстве мы собираемся сделать это, используя переменные в CSS.

У нас будет 3 разных варианта темы — Auto (Авто), Light (Светлая) и Dark (Темная). Темы Light и Dark говорят сами за себя, но тема Auto будет использовать настройку темы операционной системы, чтобы решить, будет ли сайт светлым или темным.

Я не буду показывать вам, как создать этот конкретный макет или включить его в наш контент, вот пример того, что мы могли бы создать:

Светлая и темная тема

Добавление HTML

Начнем с HTML, мы можем представить атрибуте value в теге option как об идентификаторе для каждой темы:

Добавление CSS

Давайте теперь добавим немного CSS к тегу body, здесь вы указываете свои цвета для Light темы с помощью CSS-переменных:

Затем вы можете использовать свои CSS-переменные во всей таблице стилей — это ключ к тому, как наше решение будет работать. Например, вы можете сделать:

Мы собираемся реализовать темную тему, просто заменив значения объявленных выше переменных в тех случаях, когда мы собираемся использовать темную тему. Добавим этот CSS код:

Теперь, если вы добавите класс theme-dark к своему элементу, вы увидите, что темная тема работает. Вскоре мы будем использовать JavaScript для переключения этого значения, но давайте сейчас реализуем нашу опцию Auto:

@media (prefers-color-scheme: dark) < body.theme-auto < --background-color: var(--dark-background-color); --text-color: var(--dark-text-color); >>

Вышеупомянутый CSS использует Media Queries, который проверяет, предпочитает ли операционная система темную тему, и если да, мы хотим применить вложенный набор правил для body.theme-auto .

По сути, мы говорим: «Предпочитает ли операционная система темный режим и есть ли у нее класс theme-auto? Если да, давайте использовать темный режим».

Попробуйте, изменив цвет темы своей ОС, или, что еще лучше, просмотрите веб-сайт на своем телефоне с включенным темным режимом.

Добавление JavaScript

Теперь, когда наш CSS работает, мы можем перейти к работе раскрывающегося списка выбора темы. Добавим следующий JavaScript:

function applyTheme(theme) < document.body.classList.remove("theme-auto", "theme-light", "theme-dark"); document.body.classList.add(`theme-$`); > document.addEventListener("DOMContentLoaded", () => < document.querySelector("#theme").addEventListener("change", function() < applyTheme(this.value); >); >);

Здесь мы ждем, пока DOM будет готов, чтобы мы могли начать его использовать, и как только он будет готов, мы ожидаем, когда пользователь выбирает вариант в раскрывающемся списке выбора темы. После того, как пользователь изменит тему, мы удалим все существующие классы тем из (если есть), а затем просто добавим выбранную тему с помощью this.value .

Запоминание темы

Мы могли бы пойти дальше и дать браузеру возможность запоминать тему, выбранную при обновлении страницы. Для этого мы можем использовать Local Storage

Давайте добавим следующий JavaScript код, чтобы в итоге получилось следующее:

Источник

Darken Background Image in CSS

Darken Background Image in CSS

  1. Use Linear Gradient to Darken Background Image in CSS
  2. Use the background-blend-mode Property to Darken Background Image in CSS

In this article, we will introduce a few methods to darken background images in CSS.

Use Linear Gradient to Darken Background Image in CSS

We can use the CSS Linear Gradient to Darken the Background Image in CSS. The linear-gradient() function creates a background with a linear gradient. A linear gradient is a smooth transition between at least two different colors. The function takes a countless number of color parameters. We can set the direction of the gradient as the first parameter. The options of the directions are to right , to left , to bottom right , 90deg , etc. We can apply the linear gradient to the background image and set the darker color with opacity to darken the background image. We can use the rgba() function in the linear-gradient() function to set the colors. Here, we will only darken the background image without darkening other elements.

For example, select the container in CSS and use the background shorthand property to set the linear gradient and background image. Write the linear-gradient() function and give the two color stops as rgba(0, 0, 0, 0.7) . Next, use the url() function to set a background image of your choice. Use the various background properties to place the image correctly in the background. Set background-position to center , background-repeat to no-repeat , and background-size to cover . Set the height to 100% . Make sure to select the body and html tags and set the height to 100% and margin to 0 .

In the example below, we used rgba(0, 0, 0, 0.7) as the two color stops. The function rgba(0, 0, 0) equals to black color. The fourth value is the value for opacity. The value closer to 1 makes it darker and vice versa. We can adjust the opacity value according to the need to darken the background image. In this way, we can use the linear gradient to darken the background image in CSS.

body, html   height: 100%;  margin: 0; >  #background   background: linear-gradient(rgba(0, 0, 0, 0.7), rgba(0, 0, 0, 0.7)), url('https://loremflickr.com/320/240');  height: 100%;  background-position: center;  background-repeat: no-repeat;  background-size: cover; > 

Use the background-blend-mode Property to Darken Background Image in CSS

We can use the background-blend-mode property to darken the background image in CSS. The property sets the blending mode of the background. There are various options for this property. Some options are normal , multiply , darken , lighten , saturation , etc. We can use the darken option to make the background image darker. We can set the color of the background image using the rgba() function.

For example, select the background id in CSS and use the background property to set the color and the background image. Set the color as rgba(0, 0, 0, 0.7) and use a place holder image in the url() function. Use the different background properties as in the first method to set the image correctly. Next, use the background-blend-mode property and set it to darken .

In this way, we can darken the background image using the background-blend-mode property.

#background   background: rgba(0, 0, 0, 0.7) url('https://loremflickr.com/320/240');  height: 100%;  background-position: center;  background-repeat: no-repeat;  background-size: cover;  background-blend-mode: darken; > 

Источник

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