简体   繁体   English

如何防止子元素的字体大小更改以在 CSS 中拉伸父容器

[英]How to prevent font-size change of child element to stretch parent container in CSS

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:使用以下用于导航和标签的 CSS:

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.请看这里的代码: https : //codepen.io/polinq/pen/xxbgZOM所以基本上我在导航元素上设置了一个高度并删除了填充。 And centered it using flex.并使用 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%;  

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM