KARPACH

WEB DEVELOPER BLOG

How to center dynamic content?

Let’s say you have some dynamic content that you need to center. For example a few buttons:

<asp:Button ID="btnBack" runat="server" Text="Back" />
<asp:Button ID="btnSave" runat="server" Text="Save" />
<asp:Button ID="btnNext" runat="server" Text="Next" />

and let’s say in some cases you show btnSave and in some cases not.

So ideally you want to use div and margin auto for centering:

<div style="margin:0 auto;width:200px;">
    <asp:Button ID="btnBack" runat="server" Text="Back" />
    <asp:Button ID="btnSave" runat="server" Text="Save" />
    <asp:Button ID="btnNext" runat="server" Text="Next" />
</div>

But, you don’t know the exact width, since the number of buttons is variable. Of course, you can make width dynamic in the code behind. However sometimes width is difficult to calculate, so you need a better solution.

The table is a saver:

<table align="center">
    <tr>
      <td>
        <asp:Button ID="btnBack" runat="server" Text="Back" />
        <asp:Button ID="btnSave" runat="server" Text="Save" />
        <asp:Button ID="btnNext" runat="server" Text="Next" />
      </td>
    </tr>
</table>
Posted on August 14, 2008 by

Comments

Posted on 9/14/2010 03:33:10 AM by Pest

Thank you so much for this! So many people refer to CSS to center content. I wanted to center a menu in Wordpress, but the problem is that I’d center it in CSS and when I’d add an item to the menu it would become off-center. It’s ridiculous that CSS has very primitive centering! Simply adding a table did the trick. Thanks a lot!

Posted on 2/4/2011 03:33:50 AM by Adam

I tried several ways and this is the only one that worked. Thanks very much.