如何根据内容自动调整<div>高度?

OM *_*ity 65 html css

我有一个<div>需要根据其中的内容自动调整.我怎样才能做到这一点?现在我的内容已经出来了<div>

我用于div的类如下

box-centerside  {
background:url("../images/greybox-center-bg1.jpg") repeat-x scroll center top transparent;
float:left;
height:100px;
width:260px;
}
Run Code Online (Sandbox Code Playgroud)

Adi*_*Adi 78

只需写下"min-height:XXX;" 并且"溢出:隐藏;" 你将摆脱这个问题

min-height: 100px;
overflow: hidden;
Run Code Online (Sandbox Code Playgroud)

  • 即使这对我不起作用。设置最小高度和/或溢出:隐藏对我不起作用。div 只是不扩展。 (2认同)

Bar*_*der 41

尝试使用以下标记而不是直接指定高度:

.box-centerside {
  background: url("../images/greybox-center-bg1.jpg") repeat-x scroll center top transparent;
  float: left;
  min-height: 100px;
  width: 260px;
}
Run Code Online (Sandbox Code Playgroud)
<div class="box-centerside">
  This is sample content<br>
  This is sample content<br>
  This is sample content<br>
  This is sample content<br>
  This is sample content<br>
  This is sample content<br>
  This is sample content<br>
  This is sample content<br>
  This is sample content<br>
  This is sample content<br>
  This is sample content<br>
  This is sample content<br>
</div>
Run Code Online (Sandbox Code Playgroud)

  • 如果有人还在使用ie6它自己的错,它就会破碎......"我可能会认为但是我仍然需要支持那些垃圾...或者至少内容必须存活...... (14认同)
  • 我同意Walterj89,但我也不同意 - 至少应该支持IE6*,直到IE9正确出现.一般来说,我认为没有人应该支持IE. (6认同)

小智 18

写吧:

min-height: xxx;
overflow: hidden;
Run Code Online (Sandbox Code Playgroud)

然后div会自动获取内容的高度.


Hoa*_*ang 14

您可以尝试,div 标签将自动适应内部内容的高度:

height: fit-content;
Run Code Online (Sandbox Code Playgroud)


Cle*_*ton 12

我在DIV中使用了以下需要调整大小的内容:

overflow: hidden;
height: 1%;
Run Code Online (Sandbox Code Playgroud)


Ege*_*gel 8

我已经做了一些事情来为我的项目自动调整高度,我想我找到了一个解决方案

[CSS]
    overflow: auto;
    overflow-x: hidden;
    overflow-y: hidden;
Run Code Online (Sandbox Code Playgroud)

这可以附加到您的css文件中的prime div(例如warpper,但不会bodyhtml导致页面不会向下滚动)并由其他子类继承并写入它们overflow: inherit;属性.

注意:奇怪的是我的netbeans 7.2.1 IDE突出显示overflow: inherit;为,Unexpected value token inherit但所有现代浏览器都读取此属性.

这个解决方案非常有效

  • firefox 18+
  • chorme 24+
  • 即9+
  • 歌剧12+

我没有在这些浏览器的早期版本上测试它.如果有人会检查它,那将是很好的.


Sal*_*lil 6

只需使用以下

height:auto;
Run Code Online (Sandbox Code Playgroud)