
一、实现考拉商品布局
前面的文章中我们使用浮动实现了京东首页的商品布局,接下来我们使用浮动实现考拉首页的商品布局,如下图所示:

考拉官网中品牌布局的总的宽度为 1098px:

加上左右边框,总宽度为 1100px:

首先创建一个 div.content
,该 div 的宽度为 1100px,通过 margin: 0 auto
实现居中,并设置一个背景颜色,具体代码如下:
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.content {
width: 1100px;
margin: 0 auto;
height: 800px;
background-color: orchid;
}
</style>
</head>
<body>
<div class="content">
</div>
</body>
</html>
在浏览器中打开 HTML 页面:

在 div.content
中增加 5 个item,表示 5 个品牌

设置每个 item 的样式,每个 item 的宽度为 220px,高度为 168px

css
.content .item {
width: 220px;
height: 168px;
}
实现考拉官网的样式可以通过这种思路来实现:
- 首先给 item 再包裹一层
div.container
,并设置 border 为 1px。 - 接着给每个 item 设置一个 border-right 为 1px,这样最右边就会有两个 border,一个是 item 的 border,另一个是 container 的 border,因此可以把其中一个 border 取消即可。
修改 HTML 结构,在 item 外面包裹一层 div.container
,代码如下:
html
<div class="content">
<div class="container">
<div class="item">1</div>
<div class="item">2</div>
<div class="item">3</div>
<div class="item">4</div>
<div class="item">5</div>
</div>
</div>
接着给 div.container
增加一个 border 宽度为 1px,给 item 增加一个 border-right 宽度也为 1px,具体代码如下:
css
.content .container {
border: 1px solid #000;
}
.container .item {
width: 220px;
height: 168px;
border-right: 1px solid #000;
}
刷新浏览器,效果如下:

让所有的 item 水平排列,就需要添加左浮动,给 item 添加左浮动,具体代码如下:
css
.container .item {
width: 220px;
height: 168px;
/*左浮动*/
float: left;
border-right: 1px solid #000;
}
刷新浏览器,效果如下:

可以看到最后一个 item 是自动跳到第二行显示了,此时每个 item 所占据的宽度为 220px 加上 border-right,总的宽度是大于 1100px 的,所以会自动换行。
给 div.container
设置一个高度,并且给每个 item 设置 box-sizing 为 border-box,将盒子占据的宽度调整为 220px,具体代码如下:
css
.content .container {
border: 1px solid #000;
height: 168px;
}
.container .item {
width: 220px;
height: 168px;
float: left;
border-right: 1px solid #000;
box-sizing: border-box;
}
刷新浏览器,效果如下:

此时第一行的宽度只有 1098px:

而我们希望将 box 宽度设置为 1100px,这样就可以放下 5 个 item,参考上篇文章的内容,我们可以在这里设置负的 margin-right,即:
css
.content .container {
border: 1px solid #000;
height: 168px;
margin-right: -2px;
}
刷新浏览器,效果如下:

这样在一行中就可以放下 5 个 item,但是我们还需要将 container 的右边界去掉即设置为 none,代码如下:
css
.content .container {
border: 1px solid #000;
height: 168px;
margin-right: -2px;
border-right: none;
}
刷新浏览器,效果如下:

但是这样做有两个问题,第一个问题是可以看到整个 container 是往右边偏移的;第二个问题是 container 的 border-bottom 没有去掉,导致右下角会凸出一点点。

另外使用这种实现思路还需要做精准的计算,需要添加嵌套以及给每个 item 添加边框;在下篇文章中我们可以尝试其他的实现思路。