一、认识浮动
float定义:
float 属性定义元素在哪个方向浮动。以往这个属性总应用于图像,使文本围绕在图像周
围,不过在 CSS 中,任何元素都可以浮动。浮动元素会生成一个块级框,而不论它本身是何
种元素。如果浮动非替换元素,则要指定一个明确的宽度;否则,它们会尽可能地窄。
<style>
div{#设置样式
background-color: lightblue;
width: 200px;
margin: 10px;
}
div:first-child{#第一个div块元素设置float类型向左
float: left;
}
div:nth-child(2){第二个div块元素设置float类型向右
float: right;
}
div:nth-child(3){第三个div块元素设置float类型向右
float: right;
width:500px;
}
</style>
</head>
<body>
<div>欢迎来到羊驼老师课堂1</div>
<div>欢迎来到羊驼老师课堂2</div>
<div>欢迎来到羊驼老师课堂3</div>
显示效果:
注:由于第一行的宽度有限,当你第三个div宽度太长会自动排到第二行
二、浮动的原理
<style>
.div1,.div2,.div3,.div4{
height:50px;
}
.div1{
width: 200px;
background-color: #808080;
}
.div2{
width: 400px;
background-color: #0000FF;
float:left;
}
.div3{
width: 600px;
background-color: #FFFF00;
float:left;
}
.div4{
width: 400px;
background-color: green;
}
</style>
</head>
<body>
<div class="div1">div1</div>
<div class="div2">div2</div>
<div class="div3">div3</div>
<div class="div4">div4</div>
</body>
显示效果:
小结:你可以理解为一个web网站相当于一张纸,float相当于站上去的小便利贴,分为一行一行的。没写东西就可以用float,你下一行写东西就会默认到你空白的一行,一旦你这行写东西了那么这行就用不了float。纸不能空行,float必须放空白的地方。
clear:清楚浮动效果即将脱离文档流的float变为文档流
<style>
.div1,.div2,.div3,.div4{
height:50px;
}
.div1{
width: 200px;
background-color: #808080;
}
.div2{
width: 400px;
background-color: #0000FF;
float:left;
}
.div3{
width: 600px;
background-color: #FFFF00;
float:left;
}
.div4{
width: 200px;
background-color: green;
}
.clear{
clear: both; /*清除浮动*/
}
</style>
</head>
<body>
<div class="div1">div1</div>
<div class="div2">div2</div>
<div class="div3">div3</div>
<div class="clear"></div>
<div class="div4">div4</div>
</body>
显示效果:
补充:
为了减少空标签的多余,可采用给父级的伪元素进行样式清除浮动。
.clear:after { display: block; content: ‘’; clear: both; }
2.2 overflow 属性
可在浮动元素的父级添加样式 overflow:hidden;。
三、css 盒子模型:规定了元素框处理元素内容(content)、内边距(padding)、边框(border) 和 外边距(margin) 的方式
外边距(margin):就是围绕在元素边框的空白区域,设置外边距会在元素外创建额外
的“空白” 设置外边距的最简单的方法就是使用 margin 属性,这个属性接受任何长度单位、
百分数值甚至负值
属性
margin-top: 设置上方外边距。 margin-left: 设置左方外边距。 margin-right: 设置右方外边
距。 margin-bottom: 设置下方外边距。
• margin 外边距简写:
{a}: 只有一个值的时候,为 上下左右外边距都为 a 值。 {a b}: 只有两个值的时候 为上下外边距
为 a 值 左右外边距为 b 值。 {a b c}: 只有三个值的时候 为上外边距为 a 值 左右外边距为 b 值 下
外边距为 c 值。 {a b c d}:只有四个值时候 为上外边距为 a 值 右外边距为 b 值 下外边距为 c 值 左
外边距为 d 值 (口诀:顺时针,上右下左)。
内边距(padding):就是在边框和内容区之间设置内边距的最简单的方法就是使用
padding 属性,这个属性接受任何长度单位、百分数值
边框(border):就是围绕元素内容和内边距的一条或多条线,设置边框的最简单的方
法就是使用 border 属性,允许规定元素边框的样式、宽度和颜色。
• 属性
border-width: 设置边框的宽度。 border-style: 设置边框的样式。
none
: 默认值,无边框。
solid
: 定义实线边框。
double
: 定义双实线边框。
dotted
: 定义点状线边框。
dashed
:定义虚线边框。
border-color: 设置边框的颜色。
• border 边框的简写: