div高度自适应(或者大小自适应)

mac2022-06-30  54

  <div> 是一个块级元素。这意味着它的内容自动地开始一个新行。实际上,换行是 <div> 固有的唯一格式表现(摘自W3C school)。在编写页面的时候(这里是指jsp),有遇到div标签不能随着内部的内容扩充本身大小的情况,借助div标签的height和overflow属性,可以完美解决问题。

一 布局的时候设定了div的宽度和高度,但高度不够

<div style="width: 800px;height:150px;background-color: gray;margin: auto"> <div style="height: 50px;width: 200px;background-color: red;float: none">red</div> <div style="height: 40px;width: 250px;background-color: green;float: none;display: block">green</div> <div style="float: left;margin-left: 10px;margin-top: 10px"> <table border="5" bordercolor="greenyellow" style="width: 300px;height: 100px;"> <tr> <td style="border: 2px solid greenyellow;padding: 0px;" align="center" width="200"> aaaaaaaaaaaaaaaaa </td> <td style="border: 2px solid blue;padding: 0px;" align="center"> bbbbbb </td> </tr> </table> </div> </div>

  实际效果如下(firefox上):

图一

将最外围的div的height设置为auto,就能解决问题:

图二

  overflow属性则是用来控制超出容器边框范围的内容的显示方式,允许的取值有:

值描述visible默认值。内容不会被修剪,会呈现在元素框之外。hidden内容会被修剪,并且其余内容是不可见的。scroll内容会被修剪,但是浏览器会显示滚动条以便查看其余的内容。auto如果内容被修剪,则浏览器会显示滚动条以便查看其余的内容。inherit规定应该从父元素继承 overflow 属性的值。

  默认取值是visible,这就是为什么图一中table超出div的部分还是显示出来,但是div本身大小没有改变。如果不想改变div的高度,可以设置overflow为auto,效果如下:

图三

二 子元素为浮动元素

  如果被包围的因素为浮动元素(即设置了float为none的样式),这些元素脱离了文档流,所以包围图片和文本的 div 不占据空间。

<div style="width:200px;height: auto;background-color: white;margin: auto;border: 5px solid blue"> <div style="background: yellow;width: 100px;height: 50px;">不浮动的块</div> <table style="float: right;background: red"> <tr> <td width="50" height="100"> 浮动的表格 </td> </tr> </table> <div style="float: left;width: 50px;height: 50px;background: orange">浮动的块</div> <%--<div style="clear: right;"></div>--%> </div>

  事实上,如果被包围的元素为图像,也设置了浮动样式,那么结果和div、表格一样。这种情况下,可以使用clear样式实现全包含的效果,甚至是包含到哪一个元素。clear 属性定义了元素的哪边上不允许出现浮动元素。可以取值如下:

值描述left在左侧不允许浮动元素。right在右侧不允许浮动元素。both在左右两侧均不允许浮动元素。none默认值。允许浮动元素出现在两侧。inherit规定应该从父元素继承 clear 属性的值。

  如果我们想要包围元素视觉上包围所有浮动元素,应该在所有浮动元素后面添加一个空的div块,其唯一样式为clear:both

<div style="width:200px;height: auto;background-color: white;margin: auto;border: 5px solid blue"> <div style="background: yellow;width: 100px;height: 50px;">不浮动的块</div> <table style="float: right;background: red"> <tr> <td width="50" height="100"> 浮动的表格 </td> </tr> </table> <div style="float: left;width: 50px;height: 50px;background: orange">浮动的块</div> <div style="clear: both;"></div> //新添加用于控制包含的代码 </div>

  此外,通过设定clear为不同的值,可以控制包围到那个元素的效果,下面设定clear为left,表示左边不能有float元素,效果如下:

  设定空的div的clear为left后,包围效果就是包围到左边的浮动块。同样,设为right,效果和both是一样的。

转载于:https://www.cnblogs.com/lauyu/p/3807195.html

最新回复(0)