【问题标题】:Vertically and horizontally centering HTML5 Javascript垂直和水平居中 HTML5 Javascript
【发布时间】:2011-11-04 01:43:15
【问题描述】:

所以我有这个,想把它垂直和水平居中:

<div id="hd_hype_container" style="position:relative;overflow:hidden;width:600px;height:405px;">
    <script type="text/javascript" charset="utf-8" src="hd/hd.js?88618"></script>
</div>

我已经尝试了所有解决方案,但似乎没有一个对我有用。我需要在js中添加一些东西吗?

我将不胜感激。

谢谢。

【问题讨论】:

  • 您要定位脚本吗?
  • @gAMBOOKa - 脚本可能是document.write-ing 的东西。
  • 它的 javascript 用于在 600 x 405 的背景上移动/淡化文本

标签: javascript css centering vertical-alignment


【解决方案1】:

试试:

#hd_type_container {
    position: absolute;
    top: 50%;
    height: 50%;
    width: whatever;
    height: whatever; 
    margin-left: -whatever_width_is / 2;
    margin-top: -whatever_height_is / 2;
}

请记住,绝对或相对定位的元素是相对于“最近”的父容器定位的,该父容器也是绝对或相对定位的。

换句话说,如果您的div 是绝对定位的其他div 的子代,那么您将不会以屏幕为中心,而是以父div 为中心。

更新:假设您正在尝试制作某种弹出框,您可能还需要一个 overflow: hidden 指令。

【讨论】:

  • 谢谢,但它仍然不会垂直居中。目前我有:
    哪个居中很好,但即使使用您的代码,它也无法垂直工作。再次感谢。
  • 对不起,我输入了margin right而不是margin top,我的错!非常感谢!
【解决方案2】:
<div id="hd_hype_container" style="margin-top:50%;margin:0 auto;width:600px;height:405px;">
    <script type="text/javascript" charset="utf-8" src="hd/hd.js?88618"></script>
</div>

【讨论】:

    猜你喜欢
    • 2019-07-19
    • 2015-08-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多