type | title | description |
---|---|---|
tutorial |
给你的「关于」页面添加样式 |
教程:搭建你的 Astro 博客 -
添加一个 Astro 样式标签,用于在页面上设置作用域样式 |
import Checklist from '/components/Checklist.astro';
import Spoiler from '/components/Spoiler.astro';
import Box from '/components/tutorial/Box.astro';
import PreCheck from '/components/tutorial/PreCheck.astro';
import { Steps } from '@astrojs/starlight/components';
现在你已经有了一个关于自己的页面,是时候来美化它了!
- 在单页面中设置样式 - 使用 CSS 变量使用 Astro 的 <style></style>
标签,你可以为页面上的元素设置样式。你还可以通过给这些标签添加属性和指令,获得更多的样式设置方式。
```astro title="src/pages/about.astro" ins={6-11}
<html lang="zh-cn">
<head>
<meta charset ="utf-8" />
<meta name="viewport" content="width=device-width" />
<title>{pageTitle}</title>
<style>
h1 {
color: purple;
font-size: 4rem;
}
</style>
</head>
```
在你的浏览器预览中检查这三个页面。
- 页面标题是哪种颜色:
- 首页的页面标题颜色是什么?<Spoiler>黑色</Spoiler>
- 关于页面的页面标题颜色是什么?<Spoiler>紫色</Spoiler>
- 博客页面的页面标题颜色是什么?<Spoiler>黑色</Spoiler>
- 标题文字最大的是哪个页面?<Spoiler>你的关于页面</Spoiler>
:::tip
如果你无法通过肉眼判断颜色,你可以打开浏览器开发工具检查`<h1>`标题元素,并验证其应用的文本颜色。
:::
-
将类名
skill
添加到关于页面中生成的<li>
元素上,以便你可以为其添加样式。你的代码现在应该如下所示:<p>我的技能:</p> <ul> {skills.map((skill) => <li class="skill">{skill}</li>)} </ul>
-
将以下代码添加到现有的样式标签中:
<style> h1 { color: purple; font-size: 4rem; } .skill { color: green; font-weight: bold; } </style>
-
再次在浏览器中查看你的关于页面,使用肉眼观察或者浏览器检测工具来验证每个技能列表中的项目现在是否为绿色和加粗。
Astro 的 <style>
标签还可以使用 define:vars={ {...} }
指令引用 frontmatter
中的任何变量。你可以在代码围栏中定义变量,然后在样式标签中将其用作 CSS 变量使用。
```astro title="src/pages/about.astro" ins={17}
---
const pageTitle = "关于我";
const identity = {
firstName: "莎拉",
country: "加拿大",
occupation: "技术撰稿人",
hobbies: ["摄影", "观鸟", "棒球"],
};
const skills = ["HTML", "CSS", "JavaScript", "React", "Astro", "Writing Docs"];
const happy = true;
const finished = false;
const goal = 3;
const skillColor = "navy";
---
```
-
在下面的已有的
<style>
标签中更新代码,先定义skillColor
变量,然后在双括号中使用它作为 CSS 变量。<style define:vars={{skillColor}}> h1 { color: purple; font-size: 4rem; } .skill { color: green; color: var(--skillColor); font-weight: bold; } </style>
-
在浏览器预览中查看“关于”页面。你应该看到技能现在是海军蓝色
navy
,由传递给define:vars
指令的skillColor
变量设置。
```astro title="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>
```
- 在你的 frontmatter 脚本中添加任何缺失的变量定义,以便你的新
<style>
标签成功地将这些样式应用到你的技能列表中:- 文字颜色为海军蓝
- 文本是粗体
- 列表项全部大写(全部大写字母)
✅ 给我看下代码!✅
---
const pageTitle = "关于我";
const identity = {
firstName: "莎拉",
country: "加拿大",
occupation: "技术撰稿人",
hobbies: ["摄影", "观鸟", "棒球"],
};
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";
---