如何使用 CSS 将 div 定位在页面中间,同时支持动态宽度



请在此处查看jsFiddle:http://jsfiddle.net/xv9Wq/9/

我要做的是创建一个居中并支持动态宽度的标题横幅。

以前,我有一个宽度为 100% 的标题横幅包装器,然后将标题横幅居中。问题是横幅会阻止标题横幅下方的页面。

如何将标题横幅

放置在页面中心,同时支持标题横幅内的动态内容长度?

您无法将宽度未知的绝对定位元素居中,因此这里有一个解决方法。

请参阅:http://jsfiddle.net/thirtydot/xv9Wq/25/

.CSS:

#headerBanner {
    text-align: center;
    width: 100%;
    position: absolute;
    top: 40px;
    z-index: 2;
    height: 0;
}
#headerBanner > div {
    background: red;
    display: inline-block;
    /* if ie7 support is desired: */
    *display: inline;
    zoom: 1;
}

.HTML:

<div id="headerBanner">
    <div>Centered on page. Supporting dynamic width.</div>
</div>

要防止横幅覆盖内容,请尝试以下操作:http://jsfiddle.net/xv9Wq/21

最新更新