介绍
在 HTML 中,<main> 标签用于表示文档的主要内容或核心内容。它是 HTML5 中新引入的标签,通常写在 <body> 标签内。<main> 标签的内容应该是唯一的,并且与文档的中心主题直接相关。它类似于一个地标(landmark),可以快速识别并简化大型文档中的导航。
在本实验中,我们将学习如何使用 <main> 标签在 HTML 中创建一个主要内容容器。
注意:你可以在
index.html中练习编码,并学习 如何在 Visual Studio Code 中编写 HTML。请点击右下角的“Go Live”以在端口 8080 上运行 Web 服务。然后,你可以刷新 Web 8080 标签以预览网页。
设置 HTML 文件
创建一个新文件并将其命名为 index.html。在你喜欢的代码编辑器中打开它。
在 HTML 文件的 <head> 部分,添加以下代码:
<!doctype html>
<html>
<head>
<title>Creating a Main Content Container in HTML</title>
</head>
<body></body>
</html>
添加页眉和页脚
为了让我们的网页看起来更完整,我们将添加一个页眉(header)和页脚(footer)。
在你的 HTML 文件的 <body> 标签之间添加以下代码:
<header>
<h1>My Website</h1>
<nav>
<ul>
<li><a href="#">Home</a></li>
<li><a href="#">About Us</a></li>
<li><a href="#">Contact Us</a></li>
</ul>
</nav>
</header>
<main>
<p>Welcome to my website. This is the main content area.</p>
</main>
<footer>
<p>©2021 My Website. All rights reserved.</p>
</footer>
以上代码定义了一个包含导航菜单的页眉、一个 <main> 标签以及一个页脚。
向 Main 标签添加内容
现在我们已经设置了页眉和页脚,接下来可以向 <main> 标签中添加内容。
在 <main> 标签之间添加以下代码:
<main>
<h2>About Us</h2>
<p>
We are a company that specializes in web development services. Our team
consists of experienced web developers who can help you create a website
that will help your business grow.
</p>
<h2>Our Services</h2>
<ul>
<li>Web Design</li>
<li>Web Development</li>
<li>Search Engine Optimization</li>
<li>Social Media Marketing</li>
</ul>
<h2>Our Portfolio</h2>
<p>Here are some of the websites we have created:</p>
<ul>
<li><a href="#">Website 1</a></li>
<li><a href="#">Website 2</a></li>
<li><a href="#">Website 3</a></li>
</ul>
</main>
检查最终的 HTML 代码
在添加了主要内容区域后,你的 HTML 代码应该如下所示:
<!doctype html>
<html>
<head>
<title>Creating a Main Content Container in HTML</title>
</head>
<body>
<header>
<h1>My Website</h1>
<nav>
<ul>
<li><a href="#">Home</a></li>
<li><a href="#">About Us</a></li>
<li><a href="#">Contact Us</a></li>
</ul>
</nav>
</header>
<main>
<h2>About Us</h2>
<p>
We are a company that specializes in web development services. Our team
consists of experienced web developers who can help you create a website
that will help your business grow.
</p>
<h2>Our Services</h2>
<ul>
<li>Web Design</li>
<li>Web Development</li>
<li>Search Engine Optimization</li>
<li>Social Media Marketing</li>
</ul>
<h2>Our Portfolio</h2>
<p>Here are some of the websites we have created:</p>
<ul>
<li><a href="#">Website 1</a></li>
<li><a href="#">Website 2</a></li>
<li><a href="#">Website 3</a></li>
</ul>
</main>
<footer>
<p>©2021 My Website. All rights reserved.</p>
</footer>
</body>
</html>
总结
在本实验中,我们学习了如何使用 <main> 标签在 HTML 文档中创建一个主要内容容器。我们创建了一个页眉、主要内容区域和页脚,并填充了示例内容。请记住,<main> 标签的内容应该是唯一的,并且与文档的核心主题直接相关。通过使用 <main> 标签,我们可以创建一个易于识别的网站部分,帮助用户轻松导航。



