
创建响应式网站是任何前端开发人员的一项基本技能。响应式网站会根据设备和屏幕尺寸调整其布局和内容,确保在所有设备上提供良好的用户体验。在本文中,我们将引导您完成使用 html 和 css 构建基本响应式网站的过程。
开始之前,您应该对 html 和 css 有基本的了解。熟悉 css flexbox 和媒体查询也会很有帮助。
首先创建一个新的项目文件夹并添加以下文件:
打开index.html并添加你想要的基本html结构,它可以是任何内容:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>responsive website</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<header>
<h1>my responsive website</h1>
<nav>
<ul>
<li><a href="#home">home</a></li>
<li><a href="#about">about</a></li>
<li><a href="#services">services</a></li>
<li><a href="#contact">contact</a></li>
</ul>
</nav>
</header>
<main>
<section id="home">
<h2>welcome to my website</h2>
<p>this is a simple responsive website built with html and css.</p>
</section>
<section id="about">
<h2>about us</h2>
<p>we provide excellent web development services.</p>
</section>
<section id="services">
<h2>our services</h2>
<p>we offer a wide range of web development services.</p>
</section>
<section id="contact">
<h2>contact us</h2>
<p>feel free to reach out to us for any inquiries.</p>
</section>
</main>
<footer>
<p>© 2024 my responsive website</p>
</footer>
</body>
</html>
接下来,打开文件 styles.css 并开始添加一些基本样式:
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: arial, sans-serif;
line-height: 1.6;
}
header {
background: #333;
color: #fff;
padding: 1rem 0;
}
header h1 {
text-align: center;
}
nav ul {
display: flex;
justify-content: center;
list-style: none;
}
nav ul li {
margin: 0 1rem;
}
nav ul li a {
color: #fff;
text-decoration: none;
}
main {
padding: 2rem;
}
section {
margin-bottom: 2rem;
}
footer {
background: #333;
color: #fff;
text-align: center;
padding: 1rem 0;
position: fixed;
width: 100%;
bottom: 0;
}
为了使网站具有响应能力,我们将使用媒体查询。这些允许我们根据屏幕尺寸应用不同的样式。将以下媒体查询添加到 styles.css:
@media (max-width: 768px) {
nav ul {
flex-direction: column;
align-items: center;
}
nav ul li {
margin: 0.5rem 0;
}
main {
padding: 1rem;
}
}
@media (max-width: 480px) {
header h1 {
font-size: 1.5rem;
}
nav ul li {
margin: 0.25rem 0;
}
main {
padding: 0.5rem;
}
}
在网络浏览器中打开index.html并调整浏览器窗口大小以查看布局如何针对不同屏幕尺寸进行调整。您应该看到导航菜单垂直堆叠,并且内容周围的填充随着屏幕宽度的减小而减小。
立即学习“前端免费学习笔记(深入)”;
您现在已经使用 html 和 css 构建了一个简单的响应式网站!此示例涵盖了构建网页和使用媒体查询创建响应式设计的基础知识。随着您获得更多经验,您可以探索 css 网格、flexbox 和响应式图像等先进技术,以创建更复杂和动态的布局。
敬请期待!
以上就是使用 HTML 和 CSS 构建您的第一个响应式网站的详细内容,更多请关注php中文网其它相关文章!
HTML怎么学习?HTML怎么入门?HTML在哪学?HTML怎么学才快?不用担心,这里为大家提供了HTML速学教程(入门课程),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号