Reputation:
A common problem I encounter is that I want to make an element have a border on hover, but when the border comes in the element's computed height and width increase, making it visually jump and sometimes push elements. Is there a way to cure this without using max-width
and max-height
?
Fiddle: https://jsfiddle.net/xdzm9yfu/
<style>
#mydiv { background: yellow; padding: 15px; border: 0; }
#mydiv:hover { border: 1px solid black; }
</style>
<div id="mydiv">
<p>Here's an element. Watch the text jump when the border appears.</p>
</div>
Upvotes: 1
Views: 1496
Reputation: 2900
use box-sizing:border-box
to make your width and height include your border
http://www.w3schools.com/cssref/css3_pr_box-sizing.asp
border-box - The width and height properties (and min/max properties) includes content, padding and border, but not the margin
Upvotes: 0
Reputation: 1115
The easiest way to achieve this is to apply a transparent border by default:
<style>
#mydiv {
background: yellow;
padding: 15px; border: 0;
border: 1px solid rgba(0,0,0,0);
}
#mydiv:hover { border: 1px solid black; }
</style>
Upvotes: 1
Reputation: 1696
I think you need to add box-sizing: border-box;
into your CSS for #mydiv
. That means that the padding and borders are included in the elements height and widht, not in addition to.
Or.. set your border to yellow to match the content div background colour.
Upvotes: 0
Reputation: 3330
Instead of having no border when it's not being hovered, how about giving it a transparent 1px border? That way, it'll always have the same spacing, just a different color on hover.
<style>
#mydiv { background: yellow; padding: 15px; border: 1px solid transparent; }
#mydiv:hover { border-color: black; }
</style>
<div id="mydiv">
<p>Here's an element. Watch the text jump when the border appears.</p>
</div>
Upvotes: 0