Возможно ли, чтобы <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>
Есть ли способ удовлетворить оба критерия одновременно?






Вы можете обернуть display: tablediv другим 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>
Я бы, вероятно, просто разместил бы 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>