如何创建:响应式页眉

学习如何使用 CSS 创建响应式页眉。

响应式页眉

根据屏幕大小来改变页眉的设计。调整浏览器窗口的大小可查看效果。

亲自试一试

创建响应式页眉

第一步 - 添加 HTML:

<div class="header">
  <a href="#default" class="logo">CompanyLogo</a>
  <div class="header-right">
    <a class="active" href="#home">Home</a>
    <a href="#contact">Contact</a>
    <a href="#about">About</a>
  </div>
</div>

第二步 - 添加 CSS:

/* 使用灰色背景和一些内边距来设置标题样式 */
.header {
  overflow: hidden;
  background-color: #f1f1f1;
  padding: 20px 10px;
}

/* 设置标题链接的样式 */
.header a {
  float: left;
  color: black;
  text-align: center;
  padding: 12px;
  text-decoration: none;
  font-size: 18px;
  line-height: 25px;
  border-radius: 4px;
}

/* 设置 Logo 链接的样式(请注意,我们将行高和字体大小设置为相同的值,以防止字体变大时页眉增大) */
.header a.logo {
  font-size: 25px;
  font-weight: bold;
}

/* 鼠标悬停时更改背景颜色 */
.header a:hover {
  background-color: #ddd;
  color: black;
}

/* 设置活动/当前链接的样式 */
.header a.active {
  background-color: dodgerblue;
  color: white;
}

/* 将链接部分向右浮动 */
.header-right {
  float: right;
}

/* 添加媒体查询以实现响应式 - 当屏幕宽度为 500px 或更小时,将链接堆叠在一起 */
@media screen and (max-width: 500px) {
  .header a {
    float: none;
    display: block;
    text-align: left;
  }
  .header-right {
    float: none;
  }
}

亲自试一试

相关页面

教程:CSS 导航栏