自己动手构建 - 页头
由于你的网站将在不同的设备上被浏览,现在是时候创建一个能够响应多种屏幕尺寸的页面导航了!
准备好去…
- 为你的网站创建一个包含导航组件的头部
- 使导航组件具有响应性
自己动手 - 构建一个新的 Header 组件
标题为“自己动手 - 构建一个新的 Header 组件”的部分-
创建一个新的 Header 组件。在一个
<header>
元素内的<nav>
元素中,导入并使用你现有的Navigation.astro
组件。显示代码!
在
src/components/
目录下创建一个名为Header.astro
的文件src/components/Header.astro ---import Navigation from './Navigation.astro';---<header><nav><Navigation /></nav></header>
自己动手 - 更新你的页面
标题为“自己动手 - 更新你的页面”的部分-
在每个页面上,用你的新头部替换现有的
<Navigation/>
组件。显示代码!
src/pages/index.astro ---import Navigation from '../components/Navigation.astro';import Header from '../components/Header.astro';import Footer from '../components/Footer.astro';import '../styles/global.css';const pageTitle = "Home Page";---<html lang="en"><head><meta charset="utf-8" /><link rel="icon" type="image/svg+xml" href="/favicon.svg" /><meta name="viewport" content="width=device-width" /><meta name="generator" content={Astro.generator} /><title>{pageTitle}</title></head><body><Navigation /><Header /><h1>{pageTitle}</h1><Footer /></body></html> -
检查你的浏览器预览,并验证你的头部是否显示在每个页面上。它现在看起来可能没有什么不同,但如果你使用开发者工具检查预览,你会看到你的导航链接现在被
<header>
和<nav>
等元素包围。
添加响应式样式
标题为“添加响应式样式”的部分-
用 CSS 类更新
Navigation.astro
来控制你的导航链接。将现有的导航链接包裹在一个带有nav-links
类的<div>
中。src/components/Navigation.astro ------<div class="nav-links"><a href="/">Home</a><a href="/about">About</a><a href="/blog">Blog</a></div> -
将下面的 CSS 样式复制到
global.css
中。这些样式- 为移动设备设置导航链接的样式和位置
- 包含一个
expanded
类,可以切换以在移动设备上显示或隐藏链接 - 使用
@media
查询为更大的屏幕尺寸定义不同的样式
首先定义在小屏幕尺寸上应该发生什么!较小的屏幕尺寸需要更简单的布局。然后,调整你的样式以适应更大的设备。如果你先设计复杂的情况,那么你必须努力使它再次变得简单。
src/styles/global.css html {background-color: #f1f5f9;font-family: sans-serif;}body {margin: 0 auto;width: 100%;max-width: 80ch;padding: 1rem;line-height: 1.5;}* {box-sizing: border-box;}h1 {margin: 1rem 0;font-size: 2.5rem;}/* nav styles */.nav-links {width: 100%;top: 5rem;left: 48px;background-color: #ff9776;display: none;margin: 0;}.nav-links a {display: block;text-align: center;padding: 10px 0;text-decoration: none;font-size: 1.2rem;font-weight: bold;text-transform: uppercase;}.nav-links a:hover,.nav-links a:focus {background-color: #ff9776;}.expanded {display: unset;}@media screen and (min-width: 636px) {.nav-links {margin-left: 5em;display: block;position: static;width: auto;background: none;}.nav-links a {display: inline-block;padding: 15px 20px;}}
调整你的窗口大小,并观察在不同的屏幕宽度下应用的不同样式。你的头部现在通过使用 @media
查询对屏幕尺寸是响应式的。
相关资源
标题为“资源”的部分-
基于组件的设计 外部链接
-
语义化 HTML 标签 外部链接
-
移动优先设计 外部链接