How to vertically center align a text within a dynamically created asp:Label

The following code example shows how to center a text within a asp:Label using a bit of mathematics and help of CSS styles. For the horizontal align, we can simply set the CSS style, text-align to center. For vertically center align the text, we have to use some calculations and position the text accordingly.

Label lblproof = new Label();

lblproof.ID = "label2";

int width = 60;

int height = 30;

int fontSize = 12;

lblproof.Width = width;

lblproof.Height = height-(((height - fontSize) / 2)/2);

lblproof.Text = "Pueba2";

lblproof.Style["position"] = "absolute";

lblproof.Style["font-size"] = "12px";

lblproof.Style["border-bottom"] = "2px";

lblproof.Style["border-left"] = "2px";

lblproof.Style["border-top"] = "2px";

lblproof.Style["border-right"] = "2px";

lblproof.Style["border-style"] = "solid";

lblproof.Style["text-align"]= "center";

lblproof.Style["padding-top"] = (((height - fontSize) / 2) / 2).ToString()+"px";

lblproof.Style["margin-left"] = "auto";

lblproof.Style["margin-right"] = "auto";


You can change the variable values for height, width and fontSize. The mathematical calculation will take the respective values and center the text inside the label both vertically and horizontally.

No comments: