我有这样的标记
<div>
<h1 style="text-align:center;" >Heading 1</h1>
<img style="float:left;" src="logo.gif"/>
<h1 style="text-align:center;" >Heading 2</h1>
</div>
<div>
Content goes here
</div>
问题是标题 2 相对于图像后的剩余空间居中,而不是整个 div,因此它不在页面居中。
如果我使用 position:absolute 从流中删除 img,它不会下推内容而是重叠它。
最佳答案
一种方法是使用 Logo 的大小向 div 添加右填充:
<div style="padding-right: 50px;">
<img style="float:left;" src="logo.gif"/>
<h1 style="text-align:center;" >Heading</h1>
</div>
<div>
Content goes here
</div>
另一种方法是从流中删除标题。这仅适用于 Logo 高度大于标题高度的假设。还要注意图像和标题可能会重叠。
<h1 style="position: absolute; width: 100%; text-align:center;">
Heading
</h1>
<img style="float:left;" src="logo.gif"/>
<div style="clear:both;">
Content goes here
</div>
关于css - 如何使 float 元素旁边的内容相对于包含元素居中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4213609/