拿到一张设计稿,最先想到的就是如何布局。

垂直布局?水平布局?悬浮?层叠样式?

今天我们来复习一下CSS原生的布局属性——float。

float

浮动属性。

  1. 浮动是指元素悬浮在其他元素的上方,靠左或靠右排列;
  2. 浮动元素会避开其他元素的可视内容区域;
  3. 浮动元素可以是任何元素类型,可以设置margin来控制浮动元素与其他元素内容之间的距离;
  4. 被设置了float的元素无法使用left、top、right、bottom等位置属性(不生效)。

float:left;

元素向左浮动。
  • 当前元素向左向上浮动,非浮动元素向上移动;

float:right;

元素向右浮动。
  • 当前元素向右向上浮动,非浮动元素向上移动;

float:none;

默认值。元素不浮动,并会显示在其在文本中出现的位置。

float:inherit;

规定应该从父元素继承 float 属性的值。

示例:试一试


<html>
<head>
<style type="text/css">
.div1{
background-color:#f00;
}
.div2{
float:left;
background-color:#0f0;
}
.div3{
background-color:#00f;
}
.div4{
float:right;
padding:10px;
background-color:#ff0;
}
.div5{
float:inherit;
background-color:#0ff;
}
.div6{
background-color:#f0f;
}
.div7{
float:left;
background-color:#0f0;
}
.div8{
float:inherit;
background-color:#0f0;
}
</style>
</head>

<body>
<div>
<div class='div1'>div1</div>
<div class='div2'>div2</div>
<div class='div3'>div3</div>
<div class='div4'>div4
<div class='div7'>div4-1</div>
<div class='div8'>div4-2</div>
</div>
<div class='div5'>div5</div>
<div class='div6'>div6</div>
</div>
</body>

</html>

示例结果:

结论:
  1. 可以看到,div2悬浮之后,紧接着float3上移,填充了剩余位置,填充顺序是从左到右(因为div2是float:left);
  2. div4是float:right;div4悬浮之后,div5、div6上移,填充了剩余位置;
  3. div4-1是div4的子元素,div4-1是float:left,因此div4-1相对于div4悬浮,并悬浮在div4的左边;
  4. div4-2是div4的子元素,div4-2继承了div4的属性float:right,靠右悬浮,悬浮在div4的右边;

思考

用float实现一个导航菜单。