如何同时(1)阻止a占用所有可用宽度,以及(2)使其与邻居之间的边距合拢?
时间:2020-03-06 14:45:26 来源:igfitidea点击:
是否可以同时具有一个<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: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>
我可能只是将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>