cssfloat浮动怎么做(css中的float属性用法详解)

 分类:div+css教程时间:2023-09-04 07:30:06点击:

float,css的一种属性,主要属性值为:left(左浮动)、none(不浮动)、right(右浮动)、inherit(继承父元素浮动),多用于网页布局。

1、什么是浮动

网页布局时,给元素添加float属性,使得该元素脱离普通文档流,可以理解为浮起来一层,浮起来后可以进行左右浮动(向左、向右)。

2、元素如何浮动

给该元素添加float属性,其属性值可选left、right、none、inherit

  • 当属性值为left,该元素向左浮动

  • 当属性值为right,该元素向右浮动

  • none为默认属性值,该元素不浮动

  • 当属性值为inherit,该元素float的属性值从父元素继承

3、浮动的影响

  • 浮动后,设置浮动的元素可以设置宽高

  • 浮动后,浮动元素的父元素如果没有设置宽高会受影响


<!-- 只有父元素,没有任何子元素 -->
<div style="background: chocolate;border: 1px solid black"></div>

只有父元素,没有任何子元素,浏览器打开只有一个1像素的边框


<!-- 给父元素添加1个子元素 -->
<div style="background: chocolate;border: 1px solid black">
    <div style="width: 100px;height: 100px;background: forestgreen"></div>
</div>

给父元素添加1个子元素,父元素高度就被子元素撑开了


<!-- 给子元素添加float:none -->
<div style="background: chocolate;border: 1px solid black">
  <div style="width: 100px;height: 100px;background: forestgreen;float: none"></div>
</div>

给子元素添加float:none,效果不受影响


<!-- 给子元素添加float:left -->
<div style="background: chocolate;border: 1px solid black">
   <div style="width: 100px;height: 100px;background: forestgreen;float: left"></div>
</div>

给子元素添加float:left(相当于浮起来一层),父元素只剩下一个边框效果了


<!-- 给子元素添加float:right -->
<div style="background: chocolate;border: 1px solid black">
   <div style="width: 100px;height: 100px;background: forestgreen;float: right"></div>
</div>

给子元素添加float:right(和左浮动比起来,只是浮动到右边),父元素也只剩下一个边框效果了


<div style="background: chocolate;border: 1px solid black">
  <div style="width: 100px;height: 100px;background: forestgreen;float: right"></div>
  <div style="width: 100px;height: 100px;background: forestgreen;float: right"></div>
</div>

多个子元素都设置浮动,浮动在同一层,可以设置margin属性,使其分开。

上图红色边框可以使用这个float属性实现排版


<div style="background: chocolate;border: 1px solid black">
  <div style="width: 100px;height: 100px;background: forestgreen;float: right"></div>
  <div style="width: 100px;height: 100px;background: forestgreen"></div>
</div>

如果后面元素不设置浮动,会自动挤到前面去了,效果如上图。


<div style="background: chocolate;border: 1px solid black">
   <div style="width: 100px;height: 100px;background: forestgreen;float: right"></div>
   <div style="clear: both"></div>
   <div style="width: 100px;height: 100px;background: forestgreen"></div>
</div>

如果想出现如上图布局效果,则可以在浮动属性后面添加一个无样式的div属性,并添加清除浮动属性,让父级元素自动获取到高度。

注:浮动不浮动,清除不清除,最终根据甲方需求展示效果而定,不是一定就要那么做。

除注明外的文章,均为来源:老汤博客,转载请保留本文地址!
原文地址: