【问题标题】:the hover doesn't cover the whole li element in the nav悬停不会覆盖导航中的整个 li 元素
【发布时间】:2018-12-16 01:30:23
【问题描述】:

我正在尝试为导航栏中的a 元素创建悬停状态,问题是悬停颜色想要覆盖nav 的整个高度。

我尝试在 a 元素上使用 padding 来解决这个问题,但这看起来不是正确的方法,因为我一直在更改值,直到找到正确的值。

body,
html {
  margin: 0;
  padding: 0;
}

nav {
  background: black;
}
.container {
  padding: 0px;
  margin: 0px;
  list-style: none;
  color: white;
  font-weight: bold;
  font-size: 1.8rem;
  text-transform: capitalize;

  display: flex;
}
.search {
  flex: 1;
}
.search .search-input {
  width: 100%;
  font-size: 1.8rem;
  text-transform: capitalize;
}
.container a {
    text-decoration: none;
    color: white;
    padding: 0 10px 6px 10px; /*this what I use to fix it */
}
.container a:hover {
    text-decoration: none;
    color: white;
    background: red;
}
<!DOCTYPE html>
<html lang="en">

<head>
    <link rel="stylesheet" href="./css/style.css">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    <nav>
        <ul class="container">
            <li><a href="#">home</a></li>
            <li><a href="#">profile</a></li>
            <li class="search">
                <input type="text" class="search-input" placeholder="search">
            </li>
            <li><a href="#">logout</a></li>
        </ul>
    </nav>
</body>

</html>

【问题讨论】:

    标签: html css hover nav


    【解决方案1】:

    a 标签默认是一个内联元素,然后给样式display: block; 和height: 100% 以占据他们父母的全部空间。片段:

    body,
    html {
      margin: 0;
      padding: 0;
    }
    
    nav {
      background: black;
    }
    .container {
      padding: 0px;
      margin: 0px;
      list-style: none;
      color: white;
      font-weight: bold;
      font-size: 1.8rem;
      text-transform: capitalize;
    
      display: flex;
    }
    .search {
      flex: 1;
    }
    .search .search-input {
      width: 100%;
      font-size: 1.8rem;
      text-transform: capitalize;
    }
    .container a {
        text-decoration: none;
        color: white;
        display: block;
        height: 100%;
    }
    .container a:hover {
        text-decoration: none;
        color: white;
        background: red;
    }
    <nav>
      <ul class="container">
        <li><a href="#">home</a></li>
        <li><a href="#">profile</a></li>
        <li class="search">
          <input type="text" class="search-input" placeholder="search">
        </li>
        <li><a href="#">logout</a></li>
      </ul>
    </nav>

    【讨论】:

    • 从 a 元素中占据了所有空间,它们看起来非常接近,我确实使用了 padding-left 来添加一些空间并使其更具可读性。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-01-19
    • 2018-11-16
    • 1970-01-01
    • 2014-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多