Home > Web Front-end > CSS Tutorial > How to Easily Darken Element Backgrounds with CSS?

How to Easily Darken Element Backgrounds with CSS?

Patricia Arquette
Release: 2024-11-12 05:50:01
Original
559 people have browsed it

How to Easily Darken Element Backgrounds with CSS?

Making Elements Darker with CSS: A Convenient Trick

Current methods for darkening element backgrounds using CSS can be tedious, requiring the manual creation of a darker color hex code. This article presents a convenient alternative that leverages background-image to elegantly achieve the desired darkening effect.

The Problem: Tedious Manual Darkening

When hovering over a button, it is common to darken the background color to enhance user interactivity. Previously, this was achieved by specifying a darker hex code in the CSS, as shown below:

.Button:hover {
  background-color: #ALittleDarkerHex;
}
Copy after login

However, finding a suitable darker hex code can be time-consuming and imprecise.

The Solution: Background-Image Overlay

Instead of modifying the background-color property, this technique introduces a dark layer on top of the element using background-image and linear-gradient:

.button:hover {
  background-image: linear-gradient(rgb(0 0 0/40%) 0 0);
}
Copy after login

This dark overlay is applied over the existing background color, creating a subtle darkening effect without altering the text color. The 40% opacity allows the underlying background color to remain visible while reducing its intensity.

Implementation and Example

To demonstrate this technique, consider the following HTML and CSS:

<div class="button"> some text </div>
<div class="button">
Copy after login
.button {
  display: inline-block;
  color: #fff;
  padding: 10px 20px;
  font-size: 20px;
  background-color: red;
}

.button:hover {
  background-image: linear-gradient(rgb(0 0 0/40%) 0 0);
}
Copy after login

The buttons will display their original background colors, and when hovered over, a subtle darkening effect will be applied, regardless of the background color.

The above is the detailed content of How to Easily Darken Element Backgrounds with CSS?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template