CSS Basic
CSS @media any-hover Property
Photo Credit to CodeToFun
🙋 Introduction
The @media
rule in CSS is used to apply styles based on the result of one or more media queries.
The any-hover
property is a part of the media feature that allows you to detect whether any input mechanism (such as a mouse or touch device) can hover over elements.
This property is particularly useful for designing responsive websites that cater to both touch and non-touch devices.
💡 Syntax
The syntax for the any-hover
property within a @media
query is as follows:
@media (any-hover: value) {
/* CSS rules here */
}
🏠 Property Values
- none: No input mechanism can hover, or there is no input mechanism.
- hover: At least one input mechanism can hover over elements.
🎛️ Default Value
There is no default value for the any-hover media feature, as it depends on the device's capabilities. The value is determined by the device's input mechanism(s).
📝 Example Usage
📜 Basic Usage
In this example, we'll apply a different background color to a button depending on whether the device supports hovering.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS @media any-hover Example</title>
<style>
button {
padding: 10px 20px;
font-size: 16px;
}
@media (any-hover: hover) {
button {
background-color: lightblue;
}
}
@media (any-hover: none) {
button {
background-color: lightcoral;
}
}
</style>
</head>
<body>
<h1>Button Styling Based on Hover Capability</h1>
<button>Click Me!</button>
</body>
</html>
In this example, devices that can hover (like a desktop with a mouse) will see the button with a light blue background. On devices where hovering is not possible (like most touchscreens), the button will have a light coral background.
🖥️ Browser Compatibility
The any-hover
property is supported in most modern browsers, including the latest versions of Chrome, Firefox, Safari, Edge, and Opera. However, it is always advisable to test your website across different devices to ensure the best user experience.
🎉 Conclusion
The @media
any-hover
property is an excellent tool for web developers who want to create adaptive and responsive designs. By detecting whether the device supports hover, you can customize the user experience to better suit the input capabilities of the user's device. Incorporate any-hover into your CSS to build more intuitive and accessible websites.
👨💻 Join our Community:
Author
For over eight years, I worked as a full-stack web developer. Now, I have chosen my profession as a full-time blogger at codetofun.com.
Buy me a coffee to make codetofun.com free for everyone.
Buy me a Coffee
If you have any doubts regarding this article (CSS @media any-hover Property), please comment here. I will help you immediately.