将标题固定到屏幕顶部

时间:2018-07-21 19:36:03

标签: html css css3 flexbox

我有一个标题栏,存放着我的导航栏和一张图像。这是白色背景上的黑色标头。

<header id="header">
  <img id="header-img" src="https://ruwix.com/rubiks-cube-image.php?n=4&fl=xpxyowrrbygywygowbgwyowrrxyorgybrrwyrwybwyowbgwb&bg=AABBBB&m=xy&f=png&size=200&b=40&d=5" height=100 width=100>
  <nav id="nav-bar">
    <ul>
      <li><a class="nav-link" href="#home">Home</a></li>
      <li><a class="nav-link" href="#about">About</a></li>
      <li><a class="nav-link" href="#catalogue">Catalogue</a></li>
    </ul>
  </nav>
</header>

我希望将其固定在屏幕顶部,以便始终显示在屏幕上。

到目前为止,我的CSS是

.nav-list-link {
  display: inline;
  padding-left: 10px;
}

#header {
  display: flex;
  position: fixed;
  width: 100%;
  background-color: black;
}

页面的其余部分将在页面后面升起。当我将宽度调整为100%时,它会扩展到整个行的长度,但左侧会留一些空间。另外,在它上面还有一个我似乎无法缩小的空间。

我希望页眉位于页面顶部,顶部或侧面没有多余的空间。

3 个答案:

答案 0 :(得分:1)

我已解决了该问题并改进了您的代码

body {margin:0;}

.navbar {
  overflow: hidden;
  background-color: #333;
  position: fixed;
  top: 0;
  width: 100%;
}

.navbar a {
  float: left;
  display: block;
  color: #f2f2f2;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
  font-size: 17px;
}

.navbar a:hover {
  background: #ddd;
  color: black;
}

.main {
  padding: 16px;
  margin-top: 30px;
  height: 1500px; /* Used in this example to enable scrolling */
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>

</style>
</head>
<body>
<header>

<div class="navbar">
<img id="header-img" src="https://ruwix.com/rubiks-cube-image.php?n=4&fl=xpxyowrrbygywygowbgwyowrrxyorgybrrwyrwybwyowbgwb&bg=AABBBB&m=xy&f=png&size=200&b=40&d=5" height=50 width=50 style="float: left">
  <a href="#home">Home</a>
  <a href="#news">News</a>
  <a href="#contact">Contact</a>
</div>
</header>

<div class="main">
  <h1>Fixed Top Navbar</h1>
  <h2>Scroll this page to see the effect</h2>
  <h2>The navigation bar will stay at the top of the page while scrolling</h2>
</div>

</body>
</html>

答案 1 :(得分:0)

我看到您的CSS中有一个类,但它不在您认为应该的ul标签中。您剩下的空间可能是CSS中的padding-left:10px,请留意。

答案 2 :(得分:0)

在标头选择器上,删除width属性并添加以下属性:

#header {
  display: flex;
  position: fixed;
  top: 0; 
  left: 0; 
  right: 0;
  background-color: black;
}

这会将它固定在浏览器窗口的顶部