如何创建一个适用于所有设备(PC、笔记本电脑、平板电脑和手机)的响应式网站?
响应式网站可以在任何设备上运行,无论是台式机、平板电脑还是手机。为了设置响应性,我们使用媒体查询。
创建页眉容器
为页眉创建一个div
<div class="header"> <h1>Website ↶</h1> </div>
设置页眉样式
使用text-align属性将页眉文本居中 −
.header { padding: 80px; text-align: center; background: #7b1abc; color: white; }
创建导航菜单
<nav>用于创建导航菜单 −
<nav> <a class="links selected" href="#"> Home</a> <a class="links" href="#"> Login</a> <a class="links" href="#"> Register</a> <a class="links" href="#"> Contact Us</a> <a class="links" href="#">More Info</a> </nav>
创建正文内容
使用<main>并放置您希望在网站上显示的文本 −
<main> <h2>Sample Heading</h2> <h5>Published in January</h5> <p> Lorem ipsum dolor sit amet consectetur adipisicing elit. Eum, autem. </p> <br /> <h2>Sample Heading</h2> <h5>Published in march</h5> <p> Lorem ipsum dolor sit amet consectetur adipisicing elit. Unde quo minus fugiat tempora quae ratione dignissimos exercitationem voluptate officiis reiciendis. </p> </main>
创建页脚
页脚位于底部。版权文本也可以在页脚中看到 −
<div class="footer"> <h2>Footer ↷</h2> </div>
设置页脚样式
使用text-align属性和center值将页脚文本居中 −
.footer { padding: 20px; text-align: center; color: white; background: rgb(255, 0, 0); }
设置响应性
媒体查询用于设置响应性。当屏幕尺寸小于830px时,宽度设置为100%。此外,链接的display属性值设置为block −
@media screen and (max-width: 830px) { div, main { width: 100%; text-align: center; } .links { display: block; }
示例
要创建一个适用于所有设备的响应式网站,代码如下所示:
<!DOCTYPE html> <html> <head> <title>Page Title</title> <style> * { box-sizing: border-box; } body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; margin: 0; } .header { padding: 80px; text-align: center; background: #7b1abc; color: white; } .header h1 { font-size: 40px; } nav { width: 100%; background-color: rgb(39, 39, 39); overflow: auto; height: auto; } .links { display: inline-block; text-align: center; padding: 14px; color: rgb(178, 137, 253); text-decoration: none; font-size: 17px; } .links:hover { background-color: rgb(100, 100, 100); } .selected { background-color: rgb(0, 18, 43); } main { background-color: white; padding: 20px; } .footer { padding: 20px; text-align: center; color: white; background: rgb(255, 0, 0); } @media screen and (max-width: 830px) { div, main { width: 100%; text-align: center; } .links { display: block; } } </style> </head> <body> <div class="header"> <h1>Website ↶</h1> </div> <nav> <a class="links selected" href="#"> Home</a> <a class="links" href="#"> Login</a> <a class="links" href="#"> Register</a> <a class="links" href="#"> Contact Us</a> <a class="links" href="#">More Info</a> </nav> <main> <h2>Sample Heading</h2> <h5>Published in January</h5> <p> Lorem ipsum dolor sit amet consectetur adipisicing elit. Eum, autem. </p> <br /> <h2>Sample Heading</h2> <h5>Published in march</h5> <p> Lorem ipsum dolor sit amet consectetur adipisicing elit. Unde quo minus fugiat tempora quae ratione dignissimos exercitationem voluptate officiis reiciendis. </p> </main> <div class="footer"> <h2>Footer ↷</h2> </div> </body> </html>
广告