【问题标题】:How to vertically align div text?如何垂直对齐div文本?
【发布时间】:2014-02-11 05:04:20
【问题描述】:

我有 2 个 div 并排浮动。

左边的div是零件号,只有一行。右边的 div 是产品描述,可以有多行。

当右 div 增长到 2 行或更多行时,如何垂直对齐左 div 文本。

这里是代码。

<td>
   <div class="prodNumber left partNumSizexSmall">
      <a href="link" style="color:blue;text-decoration:underline;"><b>PartNum</b></a>
   </div>
   <div class="prodDesc xsmallDesc left">
      ProductDescription1
   </div>
</td>

这里是 CSS

.left {
    float: left;
}
.prodNumber {

}

.prodDesc {
    padding-left: 8px;
    padding-right: 8px;
}
.partNumSizexSmall {
    min-width: 50px;
}
.xsmallDesc {
    max-width: 550px;
}

【问题讨论】:

标签: javascript jquery css html


【解决方案1】:

使用表格而不是 div

         <td>
            <table>
                <tr>
                    <td class="prodNumber left partNumSizexSmall">
                        <a href="link" style="color: blue; text-decoration: underline;"><b>PartNum</b></a>
                    </td>
                    <td class="prodDesc xsmallDesc left">
                        ProductDescription1 ProductDescription1 ProductDescription1 ProductDescription1
                        ProductDescription1 ProductDescription1 ProductDescription1 ProductDescription1
                        Product Description1 Product Description1 Product Description1 Product Description1
                    </td>
                </tr>
            </table>
        </td>

【讨论】:

    【解决方案2】:

    使其内容居中的 div 需要 display: table-cell

    .center_me {
        height: 200px;
        vertical-align: middle; 
        display:table-cell;
    }
    

    display:table-cell 允许元素垂直对齐子元素,因此它必须在父元素上才能使子元素垂直对齐。

    这是working JSFiddle demo

    【讨论】:

      【解决方案3】:

      使用行高。

      $("document").ready(function(){
          var newheight = $(".prodDesc").height();
          var newheight2 = $(".prodNumber").height();
         if( newheight > newheight2 ){
              $(".prodNumber").css("line-height", newheight);
          }else if( newheight2 > newheight ){
               $(".prodDesc").css("line-height", newheight2);
          }
      });
      

      应该可以,但我没有测试它。对不起。

      【讨论】:

      • 不适用于多行文本,这正是 OP 所说的。
      • 好点在编辑。在多线之前,我只考虑右侧。那应该更好。如果没有,我让其他人回答。感谢您指出这一点。
      【解决方案4】:

      最成熟的解决方案是将主容器应用为 display:table;和孩子作为显示:表格单元格。由于根据您的要求,您希望 prodNumber 和 prodDesc 相互依赖,因此请添加一个包含这两个元素的外部包装。在此处查看工作文件:urlhttp://jsfiddle.net/wZ3n3/

      PS:追加更多文字。

      希望你得到答案。

      【讨论】:

        【解决方案5】:

        使用类似的东西

        <div align="center">
        This is some text!
        </div>
        

        【讨论】:

        猜你喜欢
        • 2012-12-09
        • 1970-01-01
        • 2021-03-12
        • 2016-11-03
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多