【问题标题】:Text will not align to top of div文本不会与 div 顶部对齐
【发布时间】:2015-02-12 08:02:36
【问题描述】:

我尝试了垂直对齐、顶部边距、顶部、填充、定位和任何我能想到的技巧,但在任何情况下我都无法将文本放在 div 的顶部。我以前从未遇到过这种情况,所以我觉得我忽略了一些愚蠢的东西......

重要的东西:

HTML

        <div id="login">
            <div class="row20">
                <p class="gray1">username</p>
            </div>
            <div class="row20">
                <p class="gray1">password</p>
            </div>
            <div class="row20">
                <p class="gray1">new here? | forgot password?</p>
            </div>
        </div>

CSS

 #login {
    position: absolute;
    border: 1px solid #ccc;
    height: 73px;
    width: 260px;
    left: 620px;
    top: 3px;
    vertical-align: top;
    padding: 0px;
    margin-top: 0px;
}
div.row20 {
    height: 20px;
    border: 1px solid #cccccc;
}
p.gray1 {
    font-size: 14px;
    color: #444444;
}

我已经从我的代码中删除了所有将文本推送到这些 div 顶部的尝试,因为它们都不起作用。但是,我确实尝试了我能找到的一切。我希望“row20” div 用作我的表单的对齐方式。如果我使用 br,会使文本框与文本对齐变得更加困难。出于某种原因,p 文本显示在距父 div 顶部约 18px 处。我所做的一切都没有改变...

【问题讨论】:

    标签: html css alignment vertical-alignment text-alignment


    【解决方案1】:

    您在row20 中具有高度,因此您在对齐时遇到困难,请使用 line-height:

    p.gray1{
       font-size: 14px;
       color: #444444;
       line-height: 20px;/*or something that fits your align*/
       margin: 0;/*remove default margins*/
       padding: 0;
    }
    

    #login {
        position: absolute;
        border: 1px solid #ccc;
        height: 73px;
        width: 260px;
        left: 620px;
        top: 3px;
        vertical-align: top;
        padding: 0px;
        margin-top: 0px;
    }
    div.row20 {
        height: 20px;
        border: 1px solid #cccccc;
    }
    p.gray1 {
        font-size: 14px;
        color: #444444;
      margin: 0;
      padding: 0;
      line-height: 20px;
    }
            <div id="login">
                <div class="row20">
                    <p class="gray1">username</p>
                </div>
                <div class="row20">
                    <p class="gray1">password</p>
                </div>
                <div class="row20">
                    <p class="gray1">new here? | forgot password?</p>
                </div>
            </div>

    【讨论】:

    • 谢谢。使用 line-height: 20px 实际上将我的文本一直推到父 div 下方。所以我使用 line-height: 0x;哪个有效。
    【解决方案2】:

    您的内部p 元素溢出了div 容器,因为它具有顶部和底部默认margins,因此您应该删除它以满足您的需要:

    p.gray1 { margin:0; }
    

    JSFiddle

    【讨论】:

    • 看...我告诉过你这很愚蠢。 :-) 我试过这个,但我一定有一些干扰它的东西,当没有任何效果时我把它去掉了。这很有效,因为它应该有。
    • @user3797346 :很高兴为您提供帮助
    【解决方案3】:

    如果您想知道如何解决这些问题,最好尝试在 firefox 中使用 firebug 扩展,然后尝试您的代码,您也可以更改值并立即查看结果,这样您就不会再混淆了。

    【讨论】:

      猜你喜欢
      • 2017-01-28
      • 2020-09-06
      • 2013-03-14
      • 1970-01-01
      • 1970-01-01
      • 2018-02-09
      • 2013-04-04
      • 1970-01-01
      • 2013-06-11
      相关资源
      最近更新 更多