Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to retain an element's hover area?

Tags:

html

css

I've been trying to create elements which will change position slightly when hovered - in this example we have a primitive attempt at a 3D button which is slightly depressed when hovered over. All works as intended, unless the top and left 3 pixels are hovered over, in which case it rapidly flickers between the two states.

Is it possible, without creating a duplicate transparent element, to make the hover area not shift with the element and eliminate this behaviour? JavaScript and JQuery solutions are okay but pure HTML/CSS would be best.

#button {
  width: 100px;
  height: 100px;
  background-color: #00f;
  box-shadow: 10px 10px 3px #aaa;
}

#button:hover {
  transform: translate(3px, 3px);
  box-shadow: 7px 7px 2.1px #888;
}
<div id="button">
</div>

JSFiddle link

like image 604
spacer GIF Avatar asked Mar 22 '18 20:03

spacer GIF


People also ask

How do I make hover stay?

You can't permanently stay as hover state using CSS as it merely defines the rules on styling the tags, classes, IDs, pseudo-classes, and states. So unfortunately, you need Javascript to solve the problem.

How do you make the hover effect stay even after Unhover?

You can use Jquery to set a class when the mouse is hovered. Then the class will remain set even after the mouse moves away.

How do you hover an element in HTML?

The :hover selector is used to select elements when you mouse over them. Tip: The :hover selector can be used on all elements, not only on links. Tip: Use the :link selector to style links to unvisited pages, the :visited selector to style links to visited pages, and the :active selector to style the active link.

How can you not affect other elements when one element is hovered?

If you have two elements in your HTML and you want to :hover over one and target a style change in the other the two elements must be directly related--parents, children or siblings. This means that the two elements either must be one inside the other or must both be contained within the same larger element.


1 Answers

You could create a pseudo element :after and style this instead:

#button {
  width: 100px;
  height: 100px;
}

#button:after {
  display: block;
  width: 100%;
  height: 100%;
  background-color: #00f;
  box-shadow: 10px 10px 3px #aaa;
  content: "";
}

#button:hover:after {
  transform: translate(3px, 3px);
  box-shadow: 7px 7px 2.1px #888;
}
<div id="button">
</div>
like image 133
Sebastian Speitel Avatar answered Oct 23 '22 03:10

Sebastian Speitel