我如何同时(1)保持<div>不占用所有可用宽度和(2)使其与邻居一起折叠边距?</div>

时间:2008-09-25 23:35:11

标签: html css

是否可以同时使用<div>(1)不占用所有可用宽度,以及(2)与其邻居折叠边距?

我最近了解到,将div设置为display:table会阻止它扩展到占用父容器的整个宽度 - 但现在我意识到这会引入一个新问题:它会停止与邻居的利润率下降。

在下面的示例中,红色div无法折叠,蓝色div太宽。

<p style="margin:100px">This is a paragraph with 100px margin all around.</p>

<div style="margin: 100px; border: solid red 2px; display: table;">
  This is a div with 100px margin all around and display:table.
  <br/>
  The problem is that it doesn't collapse margins with its neighbors.
</div>

<p style="margin:100px">This is a paragraph with 100px margin all around.</p>

<div style="margin: 100px; border: solid blue 2px; display: block;">
  This is a div with 100px margin all around and display:block.
  <br/>
  The problem is that it expands to take up all available width.
</div>

<p style="margin:100px">This is a paragraph with 100px margin all around.</p>

有没有办法同时满足这两个标准?

2 个答案:

答案 0 :(得分:1)

您可以将display: table div与另一个div打包在一起,然后将保证金放在包装div上。令人讨厌,但它确实有效。

<p style="margin:100px">This is a paragraph with 100px margin all around.</p>

<div style="margin: 100px"><div style="border: solid red 2px; display: table;">
  This is a div which had 100px margin all around and display:table, but the margin was moved to a wrapper div.
  <br/>
  The problem was that it didn't collapse margins with its neighbors.
</div></div>

<p style="margin:100px">This is a paragraph with 100px margin all around.</p>

<div style="margin: 100px; border: solid blue 2px; display: block;">
  This is a div with 100px margin all around and display:block.
  <br/>
  The problem is that it expands to take up all available width.
</div>

<p style="margin:100px">This is a paragraph with 100px margin all around.</p>

答案 1 :(得分:0)

我可能只是浮动div(以便它不占用可用的宽度),然后在必要时随后清除浮动。

<p style="margin:100px">This is a paragraph with 100px margin all around.</p>

<div style="border: solid red 2px; float: left;">
  This should work.
</div>

<p style="margin:100px;clear:both;">This is a paragraph with 100px margin all around.</p>