【问题标题】:Align contents of div to the bottom将div的内容对齐到底部
【发布时间】:2012-05-09 06:58:41
【问题描述】:

我有一个包含 2 个段落的 div。我希望段落与 div 的右下角对齐。我能够使用 text-align: right 对齐参数,但我正在努力让参数与 div 的底部对齐。

标记很简单:

<div>
   <p>content 1</p>
   <p>content 2</p>
</div>

CSS:

div{
    border: 1px red solid;
    height: 100px;
}

p{
    text-align: right;
}

我尝试在段落上使用position:absolute 并设置bottom: 0,但这会使段落由于绝对定位而相互重叠。

div 不跨越整个页面,因此段落文本应限制在 div 内。

有没有办法实现内容“自下而上”的效果?

我想要的效果是这样的(photoshopped):

上面的一个小提琴:http://jsfiddle.net/cbY6h/

【问题讨论】:

    标签: css html positioning alignment


    【解决方案1】:

    HTML

    <div class="box">
       <div class="content">
           <p>content 1</p>
           <p>content 2</p>
       </div>
    </div>​​​​​​​​​​​​​​​​​​​​​
    

    CSS

    .box {
        border: 1px red solid;
        height: 100px;
        position: relative;
    }
    
    .content {
        position: absolute;
        bottom: 0;
        right: 0;
    }
    

    将内容放置在 div 的右下角。你可以在http://jsfiddle.net/cbY6h/1/看到结果。

    【讨论】:

    • 将位置设置为绝对会使其脱离流程并导致段落内容与其他内容重叠 :( box 的宽度不应固定,因为其兄弟 div 可以具有任意宽度,但在考虑了兄弟姐妹的宽度后,它被限制在父代中。
    • 比尔的回答似乎满足你的问题。如果还有其他需要考虑的因素,请相应地编辑您的问题。
    【解决方案2】:

    .content 的位置使用相对而不是绝对。

    【讨论】:

      【解决方案3】:

      要理解的关键说明。如果您要将“框”的高度更改为 100% 而不是 100px,那么它将不起作用。如果没有将高度指定为特定的测量单位,则无法确定如何放置绝对子项。

      .box {
      border: 1px red solid;
      height: 100%;
      position: relative;
      }
      

      【讨论】:

        【解决方案4】:

        我一直在寻找类似的东西,最终使用了 flexbox 布局。

        给定以下结构

        <div>
           <p>content 1</p>
            <p>another</p>
           <p>content 2</p>
        </div>
        

        还有这种风格

        div {
            border: 1px red solid;
            height: 100px;
        
            display: flex;
        
            //align items from top to bottom 
            //[I've always thought the opposite, as rows are counted from top to bottom 
            //and columns are counted left to right. Any one have an explanation for this?]
            flex-direction: column;   
        
            //main axis align to the bottom, since we are using column for direction
            justify-content: flex-end; 
        
        }
        
        p { 
           //cross axis align towards the right. total outcome => bottom right
           align-self: flex-end; 
        }
        

        你会从图片中得到布局。

        编辑:不适用于旧版浏览器 (http://caniuse.com/flexbox)。您可以使用 Modernizer 键

        .flexbox .rest-of-your-selector { rule }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2010-10-09
          • 2021-10-25
          • 1970-01-01
          • 1970-01-01
          • 2019-10-21
          • 2011-09-25
          相关资源
          最近更新 更多