The problem boils down to line height.
You have set your <a>
to have height of 4rem
, with 2rem
font size and top and bottom margins of 1rem
each. Obviously 2 + 1 + 1 adds up to 4, so that seems like it should work, but your font size is multiplied by your line height in order to come up with the total height it actually occupies.
Given that the browser's default line height is greater than 1, and the default suggested line height for most every font is greater than 1, that almost always means you will end up with overflow like this.
Possible solutions
- Set
line-height: 1
on your <a>
. If you know the text in the <a>
won't wrap anyway, this will be fine, and you'll have no problems.
nav {
display: flex;
flex-direction: row;
flex: 1;
}
nav a {
font-size: 2rem;
position: relative;
overflow: hidden;
height: 4rem;
padding: 0rem 0.5rem 0rem 0.5rem;
border: white 1px solid;
color: white;
text-decoration: none;
background-color: black;
transition: background-color 0.5s, color 0.5s, height 0.5s;
border-radius: 0.2rem;
line-height: 1; /* add this */
}
nav a div {
margin: 1rem 0rem 1rem 0rem;
}
<nav>
<a>
<div>text</div>
</a>
</nav>
- Don't set an explicit height on
<a>
. Instead, let the height just be derived from the font size and line height. In order to keep the background color behind the whole height of the text, change its margin to padding. (In this case, take the padding you already have and add margin to it to get the new total number.) This approach is preferable if you think the text inside your link may wrap, because then you will actually want a readable line height so the lines don't squish together too much.
nav {
display: flex;
flex-direction: row;
flex: 1;
}
nav a {
font-size: 2rem;
position: relative;
overflow: hidden;
/* height: 4rem; */
padding: 1rem 0.5rem 1rem 0.5rem; /* <-- modified */
border: white 1px solid;
color: white;
text-decoration: none;
background-color: black;
transition: background-color 0.5s, color 0.5s, height 0.5s;
border-radius: 0.2rem;
}
/* nav a div {
margin: 1rem 0rem 1rem 0rem;
} */
<nav>
<a>
<div>text</div>
</a>
</nav>