I have a simple nav bar:
<nav>
<a href="#">Home</a>
<a href="#">About</a>
<a href="#">Register</a>
</nav>
with following CSS for nav and a tags:
nav
{
background-color:black;
color:white;
text-align:center;
font-size:150%;
padding:2%;
}
nav a
{
text-decoration:none;
color:white;
padding:2%;
}
nav a:hover
{
background-color:white;
color:black;
font-size:120%;
}
It looks pretty much as I want it to, except that nav container stretches on hover, because font size is larger. How can I prevent nav from stretching?
There is an easier and prettier way. You should try this instead.
nav
{
background-color:black;
color:white;
text-align:center;
font-size:150%;
}
nav a
{
text-decoration:none;
color:white;
padding:2%;
display:inline-block;
}
nav a:hover
{
background-color:white;
color:black;
transform: scale(1.2);
-webkit-transform: scale(1.2);
-ms-transform:scale(1.2);
}
Adding a "line height" prevents the parent container from changing size.
nav a
{
line-height: 5%;
text-decoration:none;
color:white;
padding:2%;
}
使用其他值而不是 %。
Please have a look at the code here: https://codepen.io/polinq/pen/xxbgZOM So essentially I put a height on the nav element and removed padding. And centered it using flex.
nav
{
background-color:black;
color:white;
text-align:center;
font-size:150%;
height: 70px;
display:flex;
align-items: center;
justify-content: center;
}
nav a
{
text-decoration:none;
color:white;
padding:2%;
}
nav a:hover
{
background-color:white;
color:black;
font-size:120%;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.