好的,我有以下 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 中,但会出现在现场;这只是为了向您展示我是如何实际操作的!
那么对于避免这种跳跃的替代解决方案有什么想法吗?我的意思是我猜这是一种常见情况。
最佳答案
您可以在 header-inner
上使用 display:inline-block
,在 header
上使用 text-align:center
>.
#header {
width: 100%;
display: inline-block;
text-align: center;
}
#header_inner {
display:inline-block;
}
更新 fiddle :http://jsfiddle.net/wprggrm2/5/
关于javascript - 如何使动态和静态内容居中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25651711/