代码之家  ›  专栏  ›  技术社区  ›  raldi

我如何同时(1)防止<div>占用所有可用宽度,以及(2)使其与其相邻的边折叠?

  •  0
  • raldi  · 技术社区  · 16 年前

    有可能有一个 <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 回复  |  直到 7 年前
        1
  •  1
  •   Jonny Buchanan    16 年前

    你可以把它包起来 display: table 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>
    
        2
  •  0
  •   Herb Caudill    16 年前

    我可能只是浮动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>