Sunday, October 3, 2010

ASP.NET Align Labels with Text

The simple task of aligning labels and text can become not so easy when you move away from using tables. In this example I'm wrapping the lables and textboxes in div and using a bit of CSS to produce the result below. The important bits are highlighted.


div{
      clear:left
      margin: 5px 0 0; padding: 1px 3px;
      width: 400px;
}
.input{
      display:block; float: left 
      margin: 0 0 5px; padding: 3px 5px;
      text-align:right;width: 130px;
}




<div>
      <asp:Label AssociatedControlID="txtOne" CssClass="input" ID="label1" runat="server"  
      Text="Text One:"></asp:Label>
      <asp:TextBox ID="txtOne" runat="server"></asp:TextBox>
</div>
<div>
     <asp:Label AssociatedControlID="txtTwo"    CssClass="input" ID="label2" runat="server"
     Text="Text Two:"></asp:Label>
     <asp:TextBox ID="txtTwo" runat="server"></asp:TextBox>
</div>
<div>
     <asp:Label AssociatedControlID="ddlOne" CssClass="input" ID="label3" runat="server" 
      Text="DropDown:"></asp:Label>
     <asp:DropDownList ID="ddlOne" runat="server">
           <asp:ListItem>Choice1</asp:ListItem>
           <asp:ListItem>Choice2</asp:ListItem>
     </asp:DropDownList>
</div>
<div>
    <asp:Label AssociatedControlID="txtThree" CssClass="input" ID="label4" runat="server"  
    Text="Text Three:"></asp:Label>
    <asp:TextBox ID="txtThree" runat="server" Rows="5" TextMode="MultiLine"></asp:TextBox>
</div>
<div>
    <asp:Label AssociatedControlID="txtFour" CssClass="input" ID="label5" runat="server"
    Text="Text Four:"></asp:Label>
    <asp:TextBox ID="txtFour" runat="server" Rows="5" TextMode="MultiLine"></asp:TextBox>
</div>