Most ASP.NET best practice guides recommend laying out pages using Div tags instead of Tables for better performance and control. With that in mind, how do you align multiple text strings in a single row?
For example, a title bar on a section of an ASP.NET page may look like this:
The centered title defines the content of this section of the page. The right-aligned title is a hyperlink that pops open a dialog and allows the user to set preferences for this section.
This layout would be easy enough to achieve with an HTML table. (Or a Silverlight StackPanel, but this example is for ASP.NET.) However, the goal here is to do it with Div tags.
As with most of ASP.NET, the primary way to achieve this desired result is using the "Guess and Check" technique I described in a prior post. If you missed it, here is a quick review:
- Guess a key word or two describing what you are trying to accomplish
- Use the results to make a guess on some code (or if you look at a result and say "it can't take 2 pages of code to accomplish this!" then repeat the prior step)
- Run (F5) to check
- Repeat until something miraculously works
(And if you have to support multiple browsers, you may have to repeat the last two steps for each browser.)
Using this technique, I found that the following Div tag provides the title bar shown above:
<!-- Empty label for blank left spacing (to center the text) -->
<asp:Label ID="EmptyLabel" runat="server"
Text=" " style="float:left;width:33%;text-align:left;background-color:#BD2E26"/>
<asp:Label ID="Label1" runat="server"
Text="Customer Management" style="float:left;width:34%;text-align:center;background-color:#BD2E26;color:White;font-family:Calibri"/>
<asp:HyperLink ID="PreferencesLink" runat="server"
Text="Preferences " />
The key to this technique is to divide the title bar into three segments. Set each segment using a float:left style. This stacks the segments together starting at the left.
Set the widths to 33%, 34%, and 33% to take up the full space within its container. Adjust as needed for the design effect you are trying to achieve.
Finally, set the text-align to the correct alignment for each segment. For the first segment, it does not matter because no text is displayed. For the middle segment use text-align:center and for the right segment use text-align:right.
Notice that you must provide some text in the empty label for this to work correctly. This codes just uses to put in a non-breaking space.
Use this technique any time you need to stack text within single line and you don't want to use a Table.