跳转到内容

为你的“关于”页面添加样式

现在你已经有了一个包含关于你内容的“关于”页面,是时候给它添加样式了!

准备好去…

  • 为单个页面上的元素设置样式
  • 使用 CSS 变量

使用 Astro 自带的 <style></style> 标签,你可以为页面上的元素设置样式。向这些标签添加属性指令可以为你提供更多设置样式的方法。

  1. 复制以下代码并将其粘贴到 src/pages/about.astro

    src/pages/about.astro
    <html lang="en">
    <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width" />
    <title>{pageTitle}</title>
    <style>
    h1 {
    color: purple;
    font-size: 4rem;
    }
    </style>
    </head>

    在浏览器预览中检查所有三个页面。

    • 哪个页面的标题颜色是

      • 你的主页?
      • 你的“关于”页面?
      • 你的博客页面?
    • 标题文本最大的页面是?

  2. 将类名 skill 添加到“关于”页面上生成的 <li> 元素中,以便为它们设置样式。你的代码现在应该如下所示

    src/pages/about.astro
    <p>My skills are:</p>
    <ul>
    {skills.map((skill) => <li class="skill">{skill}</li>)}
    </ul>
  3. 将以下代码添加到你现有的样式标签中

    src/pages/about.astro
    <style>
    h1 {
    color: purple;
    font-size: 4rem;
    }
    .skill {
    color: green;
    font-weight: bold;
    }
    </style>
  4. 再次在浏览器中访问你的“关于”页面,并通过目视检查或开发者工具验证,你的技能列表中的每个项目现在都是绿色和粗体的。

Astro 的 <style> 标签还可以使用 define:vars={ {...} } 指令引用 frontmatter 脚本中的任何变量。你可以在**代码围栏中定义变量**,然后**在样式标签中将它们用作 CSS 变量**。

  1. 通过将其添加到 src/pages/about.astro 的 frontmatter 脚本中来定义一个 skillColor 变量,如下所示

    src/pages/about.astro
    ---
    const pageTitle = "About Me";
    const identity = {
    firstName: "Sarah",
    country: "Canada",
    occupation: "Technical Writer",
    hobbies: ["photography", "birdwatching", "baseball"],
    };
    const skills = ["HTML", "CSS", "JavaScript", "React", "Astro", "Writing Docs"];
    const happy = true;
    const finished = false;
    const goal = 3;
    const skillColor = "navy";
    ---
  2. 更新下面你现有的 <style> 标签,首先定义,然后在双大括号内使用这个 skillColor 变量。

    src/pages/about.astro
    <style define:vars={{skillColor}}>
    h1 {
    color: purple;
    font-size: 4rem;
    }
    .skill {
    color: green;
    color: var(--skillColor);
    font-weight: bold;
    }
    </style>
  3. 在浏览器预览中检查你的“关于”页面。你应该看到技能现在是海军蓝色,这是由传递给 define:vars 指令的 skillColor 变量设置的。

  1. 更新你的“关于”页面上的 <style> 标签,使其与下面的标签匹配。

    src/pages/about.astro
    <style define:vars={{skillColor, fontWeight, textCase}}>
    h1 {
    color: purple;
    font-size: 4rem;
    }
    .skill {
    color: var(--skillColor);
    font-weight: var(--fontWeight);
    text-transform: var(--textCase);
    }
    </style>
  2. 在你的 frontmatter 脚本中添加任何缺少的变量定义,以便你的新 <style> 标签能成功地将这些样式应用于你的技能列表

    • 文本颜色是海军蓝
    • 文本是粗体
    • 列表项全部大写(所有字母都是大写)
✅ 给我看代码!✅
src/pages/about.astro
---
const pageTitle = "About Me";
const identity = {
firstName: "Sarah",
country: "Canada",
occupation: "Technical Writer",
hobbies: ["photography", "birdwatching", "baseball"],
};
const skills = ["HTML", "CSS", "JavaScript", "React", "Astro", "Writing Docs"];
const happy = true;
const finished = false;
const goal = 3;
const skillColor = "navy";
const fontWeight = "bold";
const textCase = "uppercase";
---
贡献 社区 赞助