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?
You could wrap the
display: tabledivwith anotherdivand put the margin on the wrapperdivinstead. Nasty, but it works.