【问题标题】:How can I center align an element correctly when it contains a child element floated right?当元素包含向右浮动的子元素时,如何正确居中对齐元素?
【发布时间】:2017-02-26 13:14:05
【问题描述】:

我有一个标题和一张图片。我希望它们都出现在同一行。我希望标题居中对齐,图像右对齐。

到目前为止,我的尝试得到了以下结果:

正如您所见,标题“生成 URL”由于图像而略微向左推。我怎样才能避免这种情况发生并保持居中?

我的 HTML 标记如下:

<h1 class="renault-title text-center bottom-margin-med">
    Generate a URL 
    <img class="pull-right" src="{{ asset('bundles/urlBuilder/images/renault_english_logo_desktop.png') }}" style="height:49px;"  alt="Renault logo">
</h1>

我正在使用 Twitter 引导程序。感谢任何帮助。

【问题讨论】:

  • 绝对定位。图像必须从流程中取出,因为它的尺寸会影响“居中”项目的位置。或者使用背景图片。没有真正的理由你必须在那里使用实际图像......在那里吗?
  • 相关的,如果不是重复的话 - stackoverflow.com/questions/4597256/…
  • 虽然浮动将元素带出正常的文档流,但像文本和图像这样的内联元素会围绕它流动。这就是为什么你看到你的文本向左偏移了与浮动图像相同的量,文本在图像周围流动。

标签: html css twitter-bootstrap alignment


【解决方案1】:

最简单的方法是将img 与position: absolute 放在一起。

@import url('https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css');

h1 {
  position: relative;
  padding: 0 170px; // Add indents equal to image width to avoid text overlapping.
  font-size: 24px;
}

h1 img {
  position: absolute;
  right: 0;
  top: 0;
}
<h1 class="renault-title text-center bottom-margin-med">
    Generate a URL 
    <img src="http://placehold.it/125x49/ffcc00/" style="height:49px;"  alt="Renault logo">
</h1>

【讨论】:

    【解决方案2】:

    根据 HTML 其余部分的外观,您可以使用列。 CodePen.

    <div class="col-md-8 col-md-offset-2">
      <h1 class="renault-title text-center bottom-margin-med">
          Generate a URL 
      </h1>
    </div>
    <div class="col-md-2">
      <img class="pull-right" src="{{ asset('bundles/urlBuilder/images/renault_english_logo_desktop.png') }}" style="height:49px;"  alt="Renault logo">
    </div>
    

    【讨论】:

      猜你喜欢
      • 2013-09-13
      • 1970-01-01
      • 2012-07-01
      • 1970-01-01
      • 2014-12-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-18
      相关资源
      最近更新 更多