tags:

views:

292

answers:

2

Is it possible to have a <div> simultaneously (1) not take up all available width and (2) collapse margins with its neighbors?

I learned recently that setting a div to display:table will stop it from expanding to take up the whole width of the parent container -- but now I realize that this introduces a new problem: it stops collapsing margins with its neighbors.

In the example below, the red div fails to collapse, and the blue div is too wide.

<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>

Is there a way to meet both criteria simultaneously?

+1  A: 

You could wrap the display: table div with another div and put the margin on the wrapper div instead. Nasty, but it works.

<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>
insin
A: 

I would probably just float the div (so that it doesn't take up available width) and then clear the float subsequently if necessary.

<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>
Herb Caudill