【问题标题】:Align text to the bottom of a div将文本与 div 底部对齐
【发布时间】:2013-06-11 23:29:36
【问题描述】:

我尝试将我的文本与 Stack Overflow 中其他帖子和答案的 div 底部对齐,我学会了使用不同的 CSS 属性来处理这个问题。但我无法完成它。基本上我的 HTML 代码是这样的:

<div style='height:200px; float:left; border:1px solid #ff0000; position:relative;'>
  <span style='position:absolute; bottom:0px;'>A Text</span>
</div>

效果是在 FF 中我只是得到垂直线(折叠方式的 div)并且文本写在它旁边。如何防止 div 折叠但宽度适合文本?

【问题讨论】:

    标签: css html text vertical-alignment


    【解决方案1】:

    弹性解决方案

    如果您想使用display: table-cell 解决方案,那就太好了。但是,我们没有破解它,而是使用display: flex; 来完成同样的任务。 flex 是有 decent support 的东西。

    .wrap {
      height: 200px;
      width: 200px;
      border: 1px solid #aaa;
      margin: 10px;
      display: flex;
    }
    
    .wrap span {
      align-self: flex-end;
    }
    <div class="wrap">
      <span>Align me to the bottom</span>
    </div>

    在上面的例子中,我们首先将父元素设置为display: flex;,然后,我们使用align-selfflex-end。这有助于您将项目推送到 flex 父级的末尾。


    旧解决方案(如果您不愿意使用flex,则有效)

    如果你想将文本对齐到底部,你不必为此写那么多属性,使用display: table-cell;vertical-align: bottom;就足够了

    div {
      display: table-cell;
      vertical-align: bottom;
      border: 1px solid #f00;
      height: 100px;
      width: 100px;
    }
    &lt;div&gt;Hello&lt;/div&gt;

    (Or JSFiddle)

    【讨论】:

    • 酷!!!而已!它也可以在没有宽度属性的情况下工作,我必须省略让 div 适合内容。谢谢!
    • @parascus 它为您节省了很多您尝试过的属性......欢迎您:)
    • @blackhawk 如果您的父包装设置为inline-block,您为什么要使用此解决方案?这是专门针对可以使用display: table-cell;的人
    • 绝妙的解决方案!
    【解决方案2】:

    您现在可以使用 Flexbox justify-content: flex-end 做到这一点:

    div {
      display: flex;
      justify-content: flex-end;
      align-items: flex-end;
      width: 150px;
      height: 150px;
      border: solid 1px red;
    }
      
    <div>
      Something to align
    </div>

    Consult your Caniuse 看看 Flexbox 是否适合你。

    【讨论】:

    • 你知道用这种方法对齐到底部left的方法吗?
    • @PrestonBadeer 只需使用 justify-content: flex-start; 或完全删除它。
    • 如何使文本居中?
    • @kkkk00999 试试justify-content: center
    • 抱歉,我没有意识到您已经回答了弹性解决方案。我添加了一个类似的,因为我的解决方案很旧。有人评论了,我认为是时候更新了。希望你不要介意。
    猜你喜欢
    • 2013-07-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-04
    • 1970-01-01
    相关资源
    最近更新 更多