April 20, 2012

Center text inside relative div with no size

Question by tomash

I have following (simplified) HTML structure:

<table>
  <tr>
    <td>
      <div class="PromptContainer">
        <span class="Prompt">Prompt text</span>
      </div>
      <input type="text" name="..."/>
    </td>
  </tr>
</table>

and CSS:

.PromptContainer{
   width: 0;
   height: 0;
   position: relative;
   margin: 0 auto;
}

.Prompt{
   bottom: 0;
   padding-left: 0;
   white-space: nowrap;
   position: absolute;
}

I want to center span element over input element. Note that I cannot change size of .PromptContainer because of edge alignment rules (.Prompt element could be aligned to any edge of input element). The text inside span element has variable length and may be longer than width of input element. I cannot use javascript to perform this task, because it is too ineffective in my case (large number of such elements).

Edit:
Image visualizing what I have and what I want to achieve is available here: enter image description here

Edit 2:
Let me describe purpose of this question. We are writing new web-based runtime for giant old application written in even older technology (which worked as windows application). We have created converter from source code of this application to our new environment (ASP.NET). All controls in this old application are absolutely positioned, so we do it in the same way. Control (e.g. table of input tags) has its position and size, as well as prompt text associated with it. Prompt text is positioned relatively to control, so we don’t know its absolute position during translation. Note that it depends on font settings, text, offset from control and edge of control to which the prompt is attached.

I’m trying to write a CSS rule to position prompt in right place. I’ve resolved almost all configurations, but I have big problem with centering.

Because of absolute positioning, I cannot use .PromptContainer with non-zero size – I only know position of control, not the .Prompt itself. Bigger .PromptCointainer would move entire control down.

Additionally prompt text longer than control width must not change size of control.

Answer by Starx

How about this?

.Prompt { display: inline-block; margin: 0 auto; }

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!