代码之家  ›  专栏  ›  技术社区  ›  mxmissile

HTML左对齐和右对齐元素

  •  3
  • mxmissile  · 技术社区  · 15 年前

    为了实现这一点,我已经做到了:

    <table style="width:100%;">
     <tr>
        <td style="width:50%;text-align: left;">left</td>
        <td style="width:50%;text-align: right;">right</td>
      </tr>
    </table>
    

    在不使用表的情况下,如何以最简单的方式(最少标记)完成这项工作?我只想将2个元素与最大的左右对齐。

    现在有数百个2列布局,但它们更适合页面布局,而且似乎有些杀伤力过度。

    2 回复  |  直到 15 年前
        1
  •  8
  •   Allain Lalonde    15 年前

    一些HTML:

    <div class="left">left</div>
    <div class="right">right</div>
    

    一些CSS:

    .left, .right {
      width: 50%; /* Floated elements technically need a width specified. */
    }
    
    .left {
      float: left;
    }
    
    .right {
      float: right;
    }
    
        2
  •  3
  •   Donut    15 年前

    像这样:

    CSS

    <style type="text/css">
    #primary {
       width: 100%;
    }
    
    .secondary {
       width: 50%;
    }
    
    .leftcolumn {
       float: left;
       text-align: left;
    } 
    
    .rightcolumn {
       float: right;
       text-align: right;
    }
    </style>
    

    HTML

    <div id="primary">
       <div class="secondary leftcolumn">
          <p>This will be on the left</p>
       </div>
       <div class="secondary rightcolumn">
          <p>This will be on the right</p>
       </div>
    </div>
    

    尽管我会改变 leftcolumn rightcolumn 特定于每个内容的内容(有利于 semantic CSS而不是结构的命名方法)。