【问题标题】:How can I center my <h1> when there is an <img /> next to it?当旁边有一个 <img /> 时,如何将我的 <h1> 居中?
【发布时间】:2012-01-06 17:54:51
【问题描述】:

我在 CSS 中创建一个像样的标题时遇到问题。我想要的是一个&lt;h1&gt; 标头,它的内容在其父&lt;div&gt; 的中心对齐。有时可能会有一个额外的标志显示为常规的&lt;img /&gt;,它应该与left对齐。

这是我的示例代码:

<div class="container">
    <div class="logo">
        <img src="http://www.oldfirestation.co.uk/logo_brand_example_86.jpg" />
        <h1>Not center?</h1>
    </div>
    <div class="more">
        This is the center
    </div>
</div>

还有我的 CSS:

body {
    background-color: #161616;
}

div.container {
    background-color: #fff;
    width: 70%;
    margin: auto;
}

div.logo img {
     width: 200px;   
    float: left;
}

h1 {
    text-align: center;
    font-size: 1.4em;
    margin: 0px auto;
    padding: 0px 0px 5px 0px;  
    width: 50%;
}

div.more {
    text-align: center;
    margin-top: 50px;
    clear: left;
}

问题是当我显示&lt;img /&gt; 时,我的&lt;h1&gt; 文本居中。如果我删除这个&lt;img /&gt; 它是......我该如何解决它??

我在 JSFiddle 上做了一个例子:http://jsfiddle.net/8B9ZF/

【问题讨论】:

标签: html css image center alignment


【解决方案1】:

你这样做:

div.logo img {
     width: 200px;   
    vertical-align:middle;
}

h1 {
    text-align: center;
    font-size: 1.4em;
    margin: 0px auto;
    padding: 0px 0px 5px 0px;  
    width: 50%;
    display:inline-block;
}

http://jsfiddle.net/8B9ZF/8/

也许你可以改变你的标记

http://jsfiddle.net/8B9ZF/24/

【讨论】:

  • 这不会使我的 h1 内容在页面中居中。它在剩余空间中居中,但我希望它在整个块中居中。
  • 您提供的第二个 jsfiddle 实际上起到了作用。通过使用position: relative; 一切都很好。 &lt;h1&gt; 完全居中,如果&lt;img /&gt; 的高度增加,它只会将下面的内容向下推。谢谢!
【解决方案2】:

如果您使图像绝对定位在 0,0 而不是浮动它,那么它不会将 H1 推离中心对齐。但是,如果图像太宽,或者标题的容器太小,您就会面临图像与文本重叠的危险。为了解决这个问题,您可能需要在容器的左侧/右侧添加一些填充

【讨论】:

  • 是的,我也想过这个问题,但是如果图像高度随后增加,它会从我的标题中长出来并覆盖下面的内容:jsfiddle.net/8B9ZF/21
【解决方案3】:

http://jsfiddle.net/8B9ZF/27/

据我所知,这应该始终有效!基本上这只是添加了溢出隐藏,这使得 h1 知道浮动元素占用的空间,所以它占用了剩余的区域!

body {
    background-color: #161616;
}

div.container {
    background-color: #fff;
    width: 70%;
    margin: auto;
}
div.logo{
overflow:hidden
}
div.logo img {
     width: 200px;   
    float: left;
}

h1 {
    text-align: center;
    font-size: 1.4em;

    padding: 0px 0px 5px 0px;  

}

div.more {
    text-align: center;
    margin-top: 50px;
    clear: left;
}

【讨论】:

  • 据我所知,这应该始终有效!享受你的编码 :) 基本上这只是添加了溢出隐藏,这使得 h1 知道浮动元素占用的空间,所以它占用了剩余的区域!
  • 对不起,如果我不清楚,但我试图让 &lt;h1&gt; 相对于 &lt;div class="container"&gt; 居中,而不是在剩余空间中居中。不过感谢您的宝贵时间.. :)
  • 如果下面有你想要的图片呢?
猜你喜欢
  • 2012-09-30
  • 2015-01-19
  • 2023-02-15
  • 1970-01-01
  • 2021-12-06
  • 1970-01-01
  • 2012-07-11
  • 1970-01-01
  • 2012-05-26
相关资源
最近更新 更多