【问题标题】:Vertically align using margin-top使用 margin-top 垂直对齐
【发布时间】:2014-02-25 07:46:38
【问题描述】:

我正在尝试使我的部门垂直居中。

我需要一些东西来告诉'margin-top'到 -50% 的部门。

你可以在这里看到它:http://jsfiddle.net/N5gsW/

我知道我做错了什么:(

谢谢

HTML

<body>
<div id="content">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent iaculis quam non massa venenatis malesuada. Ut mollis, nibh id placerat euismod, magna lectus sodales lacus, nec ultrices.
</div>

CSS

body{
margin: 0 0 0 0;
width: 100%;
height: 100%;
padding: 0 0 0 0;
}
#content{
width: 100px;
left: 50%;
margin-left: -50px;
top: 50%; 
position: fixed;
background: #0C6;
}

Javascript

$(document).ready(function() {

$('#content').each(function() {
    var parentHeight = $(this).parent().height();
    var thisHeight = $(this).height();
    var topmargin = (parentHeight - thisHeight) / 2;
    $(this).css("margin-top", topmargin);
});
})  

【问题讨论】:

  • 已编辑,不知道,抱歉。

标签: javascript alignment center


【解决方案1】:

margin top 需要是-50px,这样算

margin-top = -(height / 2)px

【讨论】:

  • 不,像这样jsfiddle.net/N5gsW/6 注意减号。您还需要加载 jquery 才能使小提琴工作。
  • 在 JSFiddle 上工作正常,但由于某种原因,当我在线上传它时它不起作用:(
【解决方案2】:

在您的 JSFiddle 中,您忘记添加 Jquery 库!

$(document).ready(function() {

    $('#content').each(function() {
        var thisHeight = $(this).height();
        var topmargin = -(thisHeight) / 2;
        $(this).css("margin-top", topmargin);
    });
})  

【讨论】:

    【解决方案3】:

    http://jsfiddle.net/N5gsW/7/

    $(document).ready(function() {
        $('#content').each(function() {
            var topmargin = $(this).height() / 2;
            $(this).css("margin-top", -topmargin);
        });
    })  
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-01-18
      • 2013-03-01
      • 2015-04-18
      • 2013-04-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-27
      相关资源
      最近更新 更多