Originally posted here!
To set styles to the webpage if the user's device input can hover over the HTML elements using CSS, you can use the @media
CSS rule and then use the hover
media CSS feature with the value of hover
. If the user's device input can hover over the HTML elements, then the CSS code block will be triggered and the styles will be applied to the webpage.
TL;DR
<!-- A simple webpage with a white `button` -->
<html>
<style>
/*
Styles to apply when the user's device input has
the ability to hover over the HTML elements
*/
@media (hover: hover) {
button {
background-color: green;
}
}
</style>
<body>
<button>Click me</button>
</body>
</html>
For example, let's say we have a webpage with a button
HTML element with a white
background color.
The HTML for that would look something like this,
<!-- A simple webpage with a white `button` -->
<html>
<body>
<button>Click me</button>
</body>
</html>
The webpage now looks like this,
Now let's change the background color of the button
to a green
color if the user's device primary input can hover over the button
HTNL element. To do that first, we can use the @media
CSS rule with the hover
CSS media feature with the value of hover
.
It can be done like this,
<!-- A simple webpage with a white `button` -->
<html>
<style>
/*
Styles to apply when the user's device input has
the ability to hover over the HTML elements
*/
@media (hover: hover) {
/* Styles goes here */
}
</style>
<body>
<button>Click me</button>
</body>
</html>
Now let's select the button
HTML elements and write the background-color
CSS property with the value of green
inside the hover
CSS media feature code block.
It can be done like this,
<!-- A simple webpage with a white `button` -->
<html>
<style>
/*
Styles to apply when the user's device input has
the ability to hover over the HTML elements
*/
@media (hover: hover) {
button {
background-color: green;
}
}
</style>
<body>
<button>Click me</button>
</body>
</html>
The webpage now looks like this,
As you can see from the above code the button
HTML element's background color is now changed to green
color which proves that the hover
CSS media feature is working as expected.
See the above code live in codesandbox.
That's all 😃.
Top comments (0)