CSS下划线悬停 - 为什么填充下划线?

时间:2016-04-16 10:43:58

标签: html css underline

我正在为我的网站设计一个导航栏,我希望在悬停时加下划线的链接。为什么下划线CSS规则适用于nav-section类?

如何阻止填充加下划线?

请参阅下面附带的代码......

body {
  font-family: "Lato","Helvetica Neue",Helvetica,Arial,sans-serif;
  font-size: 24px;
  color: #424242;
}

.title {
  float: left;
  padding: 10px;
  font-size: 30px;

}

.nav-section {
  color: #757575;
  float: left;
  padding-top: 16px;
  padding-right: 15px;
  position: relative;
  text-decoration: none;
  cursor: pointer;
}

.nav-section:hover {
  color: #616161
}


.nav-link:before {
  content: "";
  position: absolute;
  width: 100%;
  height: 2px;
  bottom: 0;
  left: 0;
  background-color: #616161;
  visibility: hidden;
  -webkit-transform: scaleX(0);
  transform: scaleX(0);
  -webkit-transition: all 0.3s ease-in-out 0s;
  transition: all 0.3s ease-in-out 0s;
}


.nav-link:hover:before {
  visibility: visible;
  -webkit-transform: scaleX(1);
  transform: scaleX(1);
}
<div class="title">Title</div>
<div class="nav-section">
  <a class="nav-link">Link 1</a>
</div>
<div class="nav-section">
  <a class="nav-link">Link 2</a>
</div>
<div class="nav-section">
  <a class="nav-link">Link 3</a>
</div>
<div class="nav-section">
  <a class="nav-link">Link 4</a>
</div>

1 个答案:

答案 0 :(得分:3)

padding用于增加元素的大小。您应该使用margin-rightmargin-top来创建所需的分隔。

body {
  font-family: "Lato","Helvetica Neue",Helvetica,Arial,sans-serif;
  font-size: 24px;
  color: #424242;
}

.title {
  float: left;
  padding: 10px;
  font-size: 30px;

}

.nav-section {
  color: #757575;
  float: left;
  margin-top: 16px;
  margin-right: 15px;
  position: relative;
  text-decoration: none;
  cursor: pointer;
}

.nav-section:hover {
  color: #616161
}


.nav-link:before {
  content: "";
  position: absolute;
  width: 100%;
  height: 2px;
  bottom: 0;
  left: 0;
  background-color: #616161;
  visibility: hidden;
  -webkit-transform: scaleX(0);
  transform: scaleX(0);
  -webkit-transition: all 0.3s ease-in-out 0s;
  transition: all 0.3s ease-in-out 0s;
}


.nav-link:hover:before {
  visibility: visible;
  -webkit-transform: scaleX(1);
  transform: scaleX(1);
}
<div class="title">Title</div>
<div class="nav-section">
  <a class="nav-link">Link 1</a>
</div>
<div class="nav-section">
  <a class="nav-link">Link 2</a>
</div>
<div class="nav-section">
  <a class="nav-link">Link 3</a>
</div>
<div class="nav-section">
  <a class="nav-link">Link 4</a>
</div>