响应式网页设计 - 网格视图

什么是网格视图?

许多网页都基于网格视图(grid-view),这意味着页面被分割为几列:

在设计网页时,使用网格视图非常有帮助。这样可以更轻松地在页面上放置元素。

响应式网格视图通常有 12 列,总宽度为 100%,并且在调整浏览器窗口大小时会收缩和伸展。

构建响应式网格视图

让我们开始构建响应式网格视图。

首先,确保所有 HTML 元素的 box-sizing 属性设置为 border-box这样可以确保元素的总宽度和高度包括内边距(填充)和边框。

在 CSS 中添加以下代码:

* {
  box-sizing: border-box;
}

请访问我们的 CSS Box Sizing 阅读有关 box-sizing 属性的更多内容。

以下例子展示了一个简单的响应式网页,其中包含两列:

25%
75%

实例

.menu {
  width: 25%;
  float: left;
}
.main {
  width: 75%;
  float: left;
}

Try It Yourself

若網頁只包含兩列,則上面的例子還不錯。

但是,我們希望使用擁有 12 列的響應式網格視圖,來更好地控制網頁。

首先,我們必須計算一列的百分比:100% / 12 列 = 8.33%。

然後,我們為 12 列中的每一列創建一個類,即 class="col-" 和一個數字,該數字定義此節應跨越的列數:

CSS:

.col-1 {width: 8.33%;}
.col-2 {width: 16.66%;}
.col-3 {width: 25%;}
.col-4 {width: 33.33%;}
.col-5 {width: 41.66%;}
.col-6 {width: 50%;}
.col-7 {width: 58.33%;}
.col-8 {width: 66.66%;}
.col-9 {width: 75%;}
.col-10 {width: 83.33%;}
.col-11 {width: 91.66%;}
.col-12 {width: 100%;}

Try It Yourself

所有這些列應向左浮動,並帶有 15px 的內邊距:

CSS:

[class*="col-"] {
  float: left;
  padding: 15px;
  border: 1px solid red;
}

每行都應被包圍在 <div> 中。行內的列數總應計算為 12:

HTML:

<div class="row">
  <div class="col-3">...</div> <!-- 25% -->
  <div class="col-9">...</div> <!-- 75% -->
</div>

行內的所有列全部都向左浮動,因此會從頁面流中移出,並將放置其他元素,就好像這些列不存在一樣。為了防止這種情況,我們會添加清除流的樣式:

CSS:

.row::after {
  content: "";
  clear: both;
  display: table;
}

我們還想添加一些樣式和顏色,使其看起來更美觀:

实例

html {
  font-family: "Lucida Sans", sans-serif;
}
.header {
  background-color: #9933cc;
  color: #ffffff;
  padding: 15px;
}
.menu ul {
  list-style-type: none;
  margin: 0;
  padding: 0;
}
.menu li {
  padding: 8px;
  margin-bottom: 7px;
  background-color :#33b5e5;
  color: #ffffff;
  box-shadow: 0 1px 3px rgba(0,0,0,0.12), 0 1px 2px rgba(0,0,0,0.24);
}
.menu li:hover {
  background-color: #0099cc;
}

Try It Yourself

Please note that when you adjust the browser window width to very small, the example web page does not look ideal. In the next chapter, you will learn how to solve this problem.