【问题标题】:jquery marginTop not working properlyjquery marginTop 无法正常工作
【发布时间】:2011-07-19 02:31:01
【问题描述】:

我正在尝试在已知高度的 div 中垂直居中未知高度的文本。我已经尝试了 css display: table-cell 选项,但它没有用,所以我使用 jQuery 来检测高度,然后在必要时应用上边距以完成居中 - 这在需要时有效进行调整,但无法将其重新调整为上边距为零。

这是我的功能:

function change_trend(){
            trend_text = $('#trends_holder img:eq(' + item_count + ')').attr('data-content');
            $('.trend_text').text(trend_text);
            var trendMargin = $('.trends_scroller').height() - $('.trend_text').innerHeight();
            $('.trend_text').css('marginTop',trendMargin);
}

变量trendMargin 始终为0 或12。如果它是零,最初,一切都设置正确。然后,如果它是 12,它会适当地设置上边距。但是,当我到达 marginTop 为零的下一个项目时,它不会将事物弹回原来的位置。我怎样才能垂直对齐这些东西?看起来垂直居中真的不应该这么难......

【问题讨论】:

  • 你能在jsFiddle上举个例子吗? .trend_text 也是块级元素吗? (div)?

标签: jquery css centering


【解决方案1】:

这样就可以了:

HTML:

<div>
    <p> Some text here <br> Some more text here. </p>
</div>

CSS:

div { 
    line-height:300px; 
}

p { 
    line-height:1em; 
    display:inline-block;        
    width:100%; 
}

要设置 DIV 的高度,请使用 line-height 而不是 height。然后,在孩子(文本的容器)上,将line-height 设置回“正常”,并设置display:inline-block(这是必要的)。

现场演示: http://jsfiddle.net/simevidas/5qXMj/1/

【讨论】:

  • 奇怪的是,虽然这在 JS Fiddle 中有效,但如果我在我的代码中实现它就不起作用。单行示例有效,但具有两行或更多行的项目仅与 div 的顶部对齐。不知道为什么。但这是一个很好的提示。我会尝试在其他项目中实现它。
  • @mheavers 您可以使用 Chrome 的开发人员工具来检查哪些 CSS 样式应用于您的元素。这样您应该能够轻松找出问题所在。
【解决方案2】:

尝试使用“margin-top”而不是“marginTop”

【讨论】:

    【解决方案3】:
    <table><tr><td>
        <p>I wont tell anyone if you dont. Inline CSS for extra points.</p>
    </td></tr></table>
    

    【讨论】:

      猜你喜欢
      • 2015-11-13
      • 2011-07-24
      • 1970-01-01
      • 2021-06-16
      • 2015-12-14
      • 2015-11-13
      • 2012-07-03
      • 2012-09-12
      相关资源
      最近更新 更多