无法使用伪类:hover设置边框

4
我正在尝试使用CSS设置文本框的边框,但是我无法做到。这是我的代码:
<input type="email" id="email" style="display:inline-block;margin-top:10px;width:180px;height:30px;border:1px solid #cccccc;border-radius:1px;padding-left:8;padding-right:8;">
<style>
#email:hover
{
box-shadow: inset 0 0 4px rgba(192,192,192,0.4);
border:1px solid #bbbbbb;
}
</style>

但是当我在内联CSS中指定无边框,然后尝试在:hover伪类中设置边框时,它就可以工作。像这样:

<input type="email" id="email" style="display:inline-block;margintop:10px;width:180px;height:30px;border-radius:1px;padding-left:8;padding-right:8;">
<style>
#email:hover
{
box-shadow: inset 0 0 4px rgba(192,192,192,0.4); 
border:1px solid #bbbbbb;
}
</style>
3个回答

4
您需要在CSS规则中使用!important
#email:hover
{
    box-shadow: inset 0 0 4px rgba(192,192,192,0.4); 
    border:1px solid #bbbbbb !important;
}

由于内联CSS始终覆盖非!important规则,因此我建议您不要使用过多的内联样式,而是将其编写到<style>块中或更好地编写到外部文件中,这样可以更轻松地覆盖您的规则而无需使用!important

#email {
    display:inline-block;
    margin-top:10px;
    width:180px;
    height:30px;
    border:1px solid #cccccc;
    border-radius:1px;
    padding-left:8;
    padding-right:8;
}

#email:hover
{
    box-shadow: inset 0 0 4px rgba(192,192,192,0.4); 
    border:1px solid #bbbbbb;
}

非常感谢。我之前尝试过,但没有成功,现在它终于成功了。再次感谢! - Madeyedexter
@Madeyedexter 我刚刚在我的回答中添加了一些内容,希望它能帮助你更好地构建你的CSS。 - bwoebi

2

内联CSS的优先级高于样式表和style标签的优先级。一种解决方法是改变你的<style>样式,但这并不推荐。以下是修改后的代码:

<style>
  #email:hover {
    box-shadow: inset 0 0 4px rgba(192,192,192,0.4); 
    border: 1px solid #bbbbbb !important;
  }
</style>

!important会覆盖任何其他的样式定义。


2

因为内联样式style具有最高的优先级。 如果您希望使用其他规则来覆盖您的内联样式,请使用!important

 #email:hover
   {
    box-shadow: inset 0 0 4px rgba(192,192,192,0.4);
    border:1px solid #bbbbbb;!important
  }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接