在上一篇博客中,我简单介绍了一下浮动和清除浮动的使用,这次以一张网页设计图(图片来源于网络)为模板来练习一下。
当然作为新手,我们要从简单的开始,以覆盖色块(使用Photoshop添加纯色图层)的形式,我将这张设计图做成了一张色块图。
开始之前,我们需要先测量一些即将使用到的数据,这里推荐使用PxCook(像素大厨),一个高效易用的自动标注工具。工具栏中的距离标注、区域标注及颜色标注等可以帮助我们测量所需数据。
开始之前,先定义三个公共类,方便后续使用。
css-index.css
/* 公共类 */
.fl{
/* 左浮动 */
float: left;
}
.fr{
/* 右浮动 */
float: right;
}
.clear{
/* 清除浮动 */
clear:both;
}
首先测得该图中安全宽度为1200px,关于网页设计宽度,可以参考知乎-酸梅干超人的回答
为了方便使用,定义最后一个公共类使盒子宽度为安全宽度且在网页居中。
css-index.css
.container
{
/* 安全宽度 */
width: 1200px;
/* 左右居中 */
margin:0 auto;
}
继续测量其他数据,不需要一次性测完,在编写过程中根据需要测量就可以嗷 O-o
Emmm关于颜色,在不同显示器上会有所差异,不必太纠结于颜色代码和我的不一样的问题。
在第一层中,只有一块蓝色,没有嵌套其他盒子。
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>结构浮动及盒模型简单练习</title>
<link rel="stylesheet" href="css/css-index.css">
</head>
<body>
<!-- floor1 -->
<div class="floor1"></div>
</body>
</html>
css-index.css
.floor1{
height: 1070px;
background-color: #1394c9;
}
从floor2开始,就需要用到我们之前在css中定义的公共类。
首先在floor2中嵌套一个我们之前定义的container类,在container类中继续嵌套我们要写的title盒子和content盒子就使得盒子宽度为安全宽度且在网页居中。
index.html
<!-- floor2 -->
<div class="floor2">
<div class="container">
<div class="title">标题</div>
<div class="content">
<div class="item fl">item1</div>
<div class="item fl">item2</div>
<!-- 清除浮动 -->
<div class="clear"></div>
</div>
</div>
</div>
在写floor2的css时会用到两个属性内边距padding和外边距margin:
属性 | 说明 |
---|---|
margin | 简写属性。在一个声明中设置所有外边距属性。 |
margin-top/bottom/left/right | 设置元素的上/下/左/右外边距。 |
属性 | 说明 |
---|---|
padding | 使用缩写属性设置在一个声明中的所有填充属性 |
padding-top/bottom/left/right | 设置元素的顶部/底部/左部/右部空白 |
css-index.css
.floor2{
padding-top: 76px;
padding-bottom: 120px;
background-color: #5bc188;
}
.floor2 .title{
height: 110px;
background-color: #fdf100;
}
.floor2 .item{
width: 550px;
height: 680px;
background-color: #fdf100;
margin: 25px;
}
在这里注意不要着急给父级元素floor2定height,当floor2中的内容填充起来后,其高度自然而然也就有了。
关于item合适的外边距margin,在浏览器中右击选择‘检查’(我用的QQ浏览器,其他浏览器中也可能是检查元素或者审查之类的)。
打开后会出现我们之前写的代码,点击item右侧会出现之前写的css,点击margin的值,用鼠标滚轮缓慢滑动,就可以得到最合适的margin啦。
floor3参照floor2
index.html
<!-- floor3 -->
<div class="floor3">
<div class="container">
<div class="title">标题</div>
<div class="content">
<div class="item fl">item1</div>
<div class="item fl">item2</div>
<div class="item fl">item3</div>
<div class="item fl">item4</div>
<!-- 清除浮动 -->
<div class="clear"></div>
</div>
</div>
</div>
css-index.css
.floor3{
padding-top: 70px;
padding-bottom: 160px;
background-color: #9e9831;
}
.floor3 .title{
height: 150px;
background-color: #9085a6;
}
.floor3 .item{
width: 260px;
height: 350px;
background-color: #9085a6;
margin: 20px;
}
可能还有些不太完善的地方,因为之前忙着。。玩去了。
所以这篇博客在草稿箱放了好久,今天才找出来改了改,可算是写完了O-o