CSS Basic
CSS @media hover Property
Photo Credit to CodeToFun
π Introduction
The @media (hover)
property in CSS is part of media queries and is used to detect whether the userβs input device supports hover capability.
This can be useful in determining how to style interactive elements like buttons and links, based on whether a device can hover or not. For example, desktop computers typically support hover, while touch devices like phones usually do not.
π‘ Syntax
The @media (hover)
property uses the following basic syntax:
@media (hover: hover) {
/* Styles for devices that support hover */
}
@media (hover: none) {
/* Styles for devices that do not support hover */
}
- hover: hover: Targets devices that support hover (like desktops).
- hover: none: Targets devices that donβt support hover (like touchscreens).
π Property Values
- hover: Applies styles to devices that support hover interactions.
- none: Applies styles to devices that do not support hover interactions.
ποΈ Default Value
The @media (hover) feature does not have a default value since it depends on the userβs device and its input capabilities.
π Example Usage
π Example 1: Changing Button Style Based on Hover Support
In this example, the background color of the button will change to blue only if the device supports hover (like on desktops). On touch devices (without hover), the background will stay green.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS @media hover Example</title>
<style>
button {
padding: 10px 20px;
background-color: green;
color: white;
border: none;
cursor: pointer;
}
@media (hover: hover) {
button:hover {
background-color: blue;
}
}
@media (hover: none) {
button {
background-color: green; /* Ensures consistent style on non-hover devices */
}
}
</style>
</head>
<body>
<h1>Button with Hover Media Query</h1>
<button>Hover me!</button>
</body>
</html>
π₯οΈ Browser Compatibility
The @media (hover)
property is supported by most modern browsers including Chrome, Firefox, Safari, Edge, and Opera. It's advisable to test for compatibility across different devices (desktops, tablets, phones) to ensure that the feature behaves as expected.
π Conclusion
The CSS @media (hover)
property is a valuable tool when designing responsive and interactive user interfaces. It allows you to detect whether a device can hover and apply styles accordingly. This is especially useful when designing for both desktop and touch devices, ensuring an optimal user experience across different platforms.
π¨βπ» 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 hover Property), please comment here. I will help you immediately.