初学者CSS导航栏,孩子比父母大?

时间:2017-07-14 01:06:32

标签: html css layout parent-child navbar

我正在学习CSS,并试图制作一个非常简单的导航栏,当鼠标悬停在它上面时会改变颜色。

我认为,如果我向子元素添加填充,则会增加其父元素的大小。但是,当我向链接元素添加填充时,它们变得比它们包含的列表项更大,所以我得到了:

nav bar

我想知道是否有人可以解释为什么会这样?我很困惑!另外,您对如何强制整个导航栏与图像中显示的灰色链接的高度有任何建议吗?

非常感谢你的时间。对此,我真的非常感激! :)

这是我的HTML:

<!DOCTYPE html>
<html>
  <head>
    <link href="styles.css" type="text/css" rel="stylesheet">
  </head>

  <body>
    <div class="nav">
      <ul>
        <li><a>Home</a></li>
        <li><a>About</a></li>
        <li><a>Other link</a></li>
        <li><a>Another link</a></li>
      </ul>
    </div>
  </body>
</html>

这是我的css:

    @CHARSET "ISO-8859-1";

* {
  padding: 0; /*I read that it's a good idea to set these to 0, to avoid unexpected differences between browsers*/
  margin: 0;
  /*border-style: solid*/
}

.nav {
  background-color: black;
  color: white;

  position: fixed;
  top: 0;

  display: inline-block;
}

.nav ul {
  list-style-type: none;
}

.nav li{
  display: inline-block;
}

.nav a {
    padding: 1em 0.5em;
}

.nav a:hover{
  background-color: Grey;
}

2 个答案:

答案 0 :(得分:0)

.nav a { padding: 1em 0.5em; }

1em是让他们变大的原因。将其更改为1px,它将为您解决问题。

https://codepen.io/julysfx/pen/weOwwr

答案 1 :(得分:0)

看看这个!
这应该足以让你入门!

您为单个项目添加了填充,但您需要做的是将display: block添加到.nav a,这是导航的所有锚标记。

&#13;
&#13;
* {
  padding: 0; /*I read that it's a good idea to set these to 0, to avoid unexpected differences between browsers*/
  margin: 0;
  /*border-style: solid*/
}

.nav {
  background-color: black;
  color: white;
  position: fixed;
  top: 0;
  display: inline-block;
}

.nav ul {
  list-style-type: none;
}

.nav li{
  display: inline-block;
}

.nav a {
  padding: 1em 0.5em;
  display: block;
  vertical-align: middle;
  text-decoration: none;
  color: white;
}

.nav a:hover{
  background-color: grey;
}
&#13;
<!DOCTYPE html>
<html>
  <head>
    <link href="styles.css" type="text/css" rel="stylesheet">
  </head>

  <body>
    <div class="nav">
      <ul>
        <li><a href="#">Home</a></li>
        <li><a href="#">About</a></li>
        <li><a href="#">Other link</a></li>
        <li><a href="#">Another link</a></li>
      </ul>
    </div>
  </body>
</html>
&#13;
&#13;
&#13;

相关问题