【问题标题】:How to center a div with dynamic & static content?如何使具有动态或静态内容的 div 居中?
【发布时间】:2014-10-28 09:22:14
【问题描述】:

好的,我有以下 HTML:

<div id="header">
    <div id="header_inner">
        <div id="header_image">
            <a href=""><img src="..."/></a>
        </div>
        <div id="header_content">
            <h1 id="header_content_h1">Dynamic Content</h1>
        </div>
    </div>
</div>

我想将 id 为 header_inner 的 div 居中。

但我的问题是 id 为 header_content 的 div 包含动态内容,因此它可以是任意宽度。

目前我通过在window.onload 使用Javascript 设置header_inner 的宽度和用于居中div 的普通css (margin:auto;) 来解决这个问题,但这会导致内容最初加载在页面的左侧,然后几毫秒后跳到中心。这种跳跃在现场网站上非常明显。

JSFiddle:http://jsfiddle.net/wprggrm2/4/

*跳转不会出现在 JSFiddle 中,但会出现在现场;这只是为了向您展示我的实际操作!

那么对于避免这种跳跃的替代解决方案有什么想法吗?我的意思是我猜这是一种常见的情况。

【问题讨论】:

  • 你滥用花车。看起来你真的不需要它们:jsfiddle.net/wprggrm2/6
  • FWIW,跳转是由于浏览器加载所有页面内容的延迟引起的,然后在页面加载后触发window.onload事件。你可以document.ready最小化这个吗?

标签: javascript html css css-float center


【解决方案1】:

您可以在header-inner 上使用display:inline-block,在header 上使用text-align:center

#header {
    width: 100%;
    display: inline-block;
    text-align: center;
}
#header_inner {
    display:inline-block;
}

更新小提琴:http://jsfiddle.net/wprggrm2/5/

【讨论】:

    【解决方案2】:

    您只需要在header-inner 元素JSFiddle 上使用max-width

    【讨论】:

      猜你喜欢
      • 2013-01-05
      • 2012-02-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多