网站响应式布局
通过上一章内容使用的一些CSS代码,我们创建了一个响应式网站布局,根据屏幕宽度的不同,该布局在两列和全宽列之间变化:
完整代码如下:
<!DOCTYPE html><html><head><meta name="viewport" content="width=device-width, initial-scale=1"><style>* {box-sizing: border-box;}body {font-family: Arial;padding: 10px;background: #f1f1f1;}/* 标题样式 */.header {padding: 30px;text-align: center;background: white;}.header h1 {font-size: 50px;}/* 导航条样式 */.topnav {overflow: hidden;background-color: #333;}/* 导航条链接样式 */.topnav a {float: left;display: block;color: #f2f2f2;text-align: center;padding: 14px 16px;text-decoration: none;}/* 改变鼠标悬停时的颜色 */.topnav a:hover {background-color: #ddd;color: black;}/* 创建两个不等列 *//* 左列 */.leftcolumn {float: left;width: 75%;}/* 右列 */.rightcolumn {float: left;width: 25%;background-color: #f1f1f1;padding-left: 20px;}/* 伪图片 */.fakeimg {background-color: #aaa;width: 100%;padding: 20px;}/* 为文章增加卡片式的阴影效果 */.card {background-color: white;padding: 20px;margin-top: 20px;}/* 在列后面清除浮动效果 */.row:after {content: "";display: table;clear: both;}/* 页脚 */.footer {padding: 20px;text-align: center;background: #ddd;margin-top: 20px;}/* 响应式布局-当屏幕宽度小于800px时,使两列堆叠在一起,而不是相邻 */@media screen and (max-width: 800px) {.leftcolumn, .rightcolumn {width: 100%;padding: 0;}}/* 响应式布局-当屏幕宽度小于400px时,使导航链接堆叠在彼此的顶部,而不是相邻 */@media screen and (max-width: 400px) {.topnav a {float: none;width: 100%;}}</style></head><body><div class="header"><h1>我的网站</h1><p>调整浏览器窗口的大小以查看效果。</p></div><div class="topnav"><a href="#">链接</a><a href="#">链接</a><a href="#">链接</a><a href="#" style="float:right">链接</a></div><div class="row"><div class="leftcolumn"><div class="card"><h2>标题</h2><h5>标题描述</h5><div class="fakeimg" style="height:200px;">图片</div><p>一些文本</p><p>这里是文章的内容。这里是文章的内容。这里是文章的内容。这里是文章的内容。这里是文章的内容。这里是文章的内容。这里是文章的内容。这里是文章的内容。这里是文章的内容。这里是文章的内容。这里是文章的内容。</p></div><div class="card"><h2>标题</h2><h5>标题描述</h5><div class="fakeimg" style="height:200px;">图片</div><p>一些文本</p><p>这里是文章的内容。这里是文章的内容。这里是文章的内容。这里是文章的内容。这里是文章的内容。这里是文章的内容。这里是文章的内容。这里是文章的内容。这里是文章的内容。这里是文章的内容。这里是文章的内容。</p></div></div><div class="rightcolumn"><div class="card"><h2>关于我</h2><div class="fakeimg" style="height:100px;">Image</div><p>我是一名热爱编程的......</p></div><div class="card"><h3>热门文章</h3><div class="fakeimg"><p>图片</p></div><div class="fakeimg"><p>图片</p></div><div class="fakeimg"><p>图片</p></div></div><div class="card"><h3>关注我</h3><p>Some text..</p></div></div></div><div class="footer"><h2>页脚</h2></div></body></html>