css - 如何使 float 元素旁边的内容相对于包含元素居中?

标签 css css-float center

我有这样的标记

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

相关文章:

html - 按顺序 float 5个不同大小的盒子,并使用CSS制作填充包装

css - 在 100% 宽度 div 内居中 div

android - 如何使用 pixate (android) 设置按钮样式

HTML - 如何使 <p> 中的文本垂直居中

javascript - magento 中用户角色和权限的事件日志

Android WebView 和 CSS 媒体查询

css - 在另一个 Div 中以表格方式 float 的 Div

css - 清除 float 有一个奇怪的结果

java - JLabel、流程布局。将 JLabel 居中?

html - 如何在 flexbox 中居中放置内容