Reputation: 230286
I'm trying to make a navbar as an exercise.
I'm using a:hover
to include a solid border around the button being hovered. However, this makes all the other buttons move by the size of the border.
What is the proper fix to this problem? I know there are others (discussed here), I specifically tried to make the border "be invisible yet take up space even when not hovered". I set border:transparent
hoping it might do what I want, but it did not show take space at all.
I know I could hand pick the border's color to be equal to the background and make it solid, but this is not what I want. Is there a sane way to solve this issue?
Upvotes: 64
Views: 89323
Reputation: 351
invisible border that occupies space
border: 2px solid rgba(255, 255, 255, 0)
Upvotes: -2
Reputation: 47
Please note that transparent border is just useful when you don't have any box-shadow on the element. Have a look at the image:
Upvotes: -1
Reputation: 979
use pseudo elements ::after
and ::before
to ceate invisible boundaries.
Upvotes: -1
Reputation: 43
Setting border-color : transparent ; does the job.
a {
border-color : transparent ;
}
a:hover {
border-color : black;
}
Upvotes: 2
Reputation: 18252
Your best option would be to add padding or margins to your element that's the same size as the border and make the border have zero width, and then show the border and remove the padding with the a:hover
selector.
Here's a sample. You can often do this with margins too.
a {
display: inline-block;
height: 2em; width: 100px;
padding: 2px;
background: #0ff;
}
a:hover {
padding: 0;
border :2px solid #000;
}
<a href="#">Hello World</a>
Upvotes: 22
Reputation: 102844
One reason this isn't working as you'd expect is because you are only applying display:block
on :hover
, it needs to be applied to the element without the :hover selector or you will get the "shifting" dimensions. It doesn't matter which display type you use, you just have to make sure they are the same, and by default <a>
is inline.
Another reason has something to do with your shorthand borders, you need to add a border type for the transparent version like solid
instead of none
.
The technique you are using is totally legit, no need for padding hacks or outline (which doesn't add dimension).
http://jsfiddle.net/Madmartigan/kwdDB/
Try this:
#wd-navbar li a {
border: medium solid transparent;
display: block;
margin: 1px;
}
#wd-navbar li a:hover {
background-color: #F5DEB3;
border: medium solid;
}
Upvotes: 5
Reputation: 944215
border:transparent
means border: transparent 0 none
If you don't specify a property when using shorthand syntax then you reset all the properties to their defaults.
You need to give it a border-style and a border-width.
Upvotes: 4
Reputation: 138180
You could use the outline
CSS property instead of your border, which acts like a border but isn't taken into account in the sizing calculations.
However, this does have some issues, not being supported by IEs 7 or earlier.
Upvotes: 4