
創建響應式網站是任何前端開發人員的一項基本技能。響應式網站會根據設備和屏幕尺寸調整其布局和內容,確保在所有設備上提供良好的用戶體驗。在本文中,我們將引導您完成使用 html 和 css 構建基本響應式網站的過程。
先決條件
開始之前,您應該對 html 和 css 有基本的了解。熟悉 css flexbox 和媒體查詢也會很有幫助。
第 1 步:設置您的項目
首先創建一個新的項目文件夾并添加以下文件:
- index.html:主要的 html 文件。
- styles.css:用于設置網站樣式的 css 文件。
第 2 步:構建 html
打開index.html并添加你想要的基本html結構,它可以是任何內容:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | <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"><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>
<p><span>立即學習</span>“<a href="https://pan.quark.cn/s/cb6835dc7db1" style="text-decoration: underline !important; color: blue; font-weight: bolder;" rel="nofollow" target="_blank">前端免費學習筆記(深入)</a>”;</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>
|
第 3 步:設計您的網站
接下來,打開文件 styles.css 并開始添加一些基本樣式:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 | * {
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;
}
|
第 4 步:使其具有響應能力
為了使網站具有響應能力,我們將使用媒體查詢。這些允許我們根據屏幕尺寸應用不同的樣式。將以下媒體查詢添加到 styles.css:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | @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;
}
}
|
第 5 步:測試您的網站
在網絡瀏覽器中打開index.html并調整瀏覽器窗口大小以查看布局如何針對不同屏幕尺寸進行調整。您應該看到導航菜單垂直堆疊,并且內容周圍的填充隨著屏幕寬度的減小而減小。
最后
您現在已經使用 html 和 css 構建了一個簡單的響應式網站!此示例涵蓋了構建網頁和使用媒體查詢創建響應式設計的基礎知識。隨著您獲得更多經驗,您可以探索 css 網格、flexbox 和響應式圖像等先進技術,以創建更復雜和動態的布局。
敬請期待!
評論一下?