Centering A SliderExtender Control In ASP.NET Web Forms

I came across this question on the forums from antrea, who had a fairly straight-forward request to center a SliderExtender control within a <div> element. I thought that the answer would be one of the usual answers involving margins, some alignment and game over.

Nope. In fact the eventual solution felt so strange and hackish that I simply had to post about it.

99 Centered Elements and a Slider Ain’t One

Everything was centered within the <div> with the exception of the Slider. So I dusted off an old Web Forms project to test this out myself and threw together a very basic example with basically every method out there to handle centering the <div> and its Slider child:

  1. <div style="text-align: center; width: 300px; margin: 0 auto;" align='center'>  
  2.     <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>  
  3.     <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>  
  4.     <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>  
  5.     <ajaxToolkit:SliderExtender ID="TextBox1_SliderExtender" runat="server" TargetControlID="TextBox1"> </ajaxToolkit:SliderExtender>  
  6. </div>  
Which appears as follows:

see slider

A Rather Unorthodox Solution

After tinkering with the element within my browsers Development Tools, I noticed that styles were being dynamically added to it that made altering any of them quite a pain. The primary style in question was:

ajax__slider_h_rail

When I attempted to change the RailCssStyle property of the SliderExtender control to a custom style that I had created to center it:
  1. <style type='text/css'> .center { margin: 0 auto; } </style>   
  2. <ajaxToolkit:SliderExtender ID="SliderExtender" runat="server" TargetControlID="Example" RailCssStyle="center" ></ajaxToolkit:SliderExtender>   
The appearance of the slider changed as expected, but not exactly for the better:

slider

But that completely removed all of the dynamically generated styles although the slider was centered. So I figured that the best method to handle this would be to actually use the dynamically generated class name and the centered class that was created to apply the dynamic styles and to center the slider within its container by using:
  1. <ajaxToolkit:SliderExtender ID="SliderExtender1"  runat="server"   TargetControlID="TextBox1"   
  2.    RailCssClass="ajax__slider_h_rail centered">  
  3. </ajaxToolkit:SliderExtender>  
Sweet Centered Victory

Sweet Centered Victory
Although this is a unorthodox method of handling this issue, it will work to center your slider and possibly get you out of a bind if you find yourself in such as precarious situation.

 


Similar Articles