Sapan Diwakar

Software developer

Follow me on Twitter Check out my code on GitHub View some of my designs on Dribbble Take a look at my Linked In profile

How to center text horizontally and vertically in a div

I had been trying to center the text in div element both vertically and horizontally. I had been searching for the solutions to this, but couldn't find anything which completely described my problem and the solution. Let me first explain what exactly I was trying to do: I was adding a div element dynamically to a web page using Javascript. The div element should have a known height and width and the text should be positioned in the center of the div element.
Let me start from the beginning.

  1. How to create a div element dynamically using `javascript`: For this, we will use the `createElement` method.
    var myDivElement = document.createElement('div');  
    You can then specify absolute position (known beforehand) in the document using css styles and associating a class with the element using:
    myDivElement.className += ' my-div-class';  
    The position can then be defined in a `css` file. Alternatively, if the position of the div element is not known beforehand, then it can be associated in the javascript code itself using: = 'absolute'; = posY + 'px'; = posX + 'px';  
    We can then add any code inside the div element using:
    myDivElement.innerHTML = "Some HTML";  
    The next step is to add the created element to the document (or any other element on the document):
    The element can also be removed later using:
  2. The next step is to align the text in the div element to center. The text can be aligned to center using the following css styles:
    vertical-align : middle;  
    text-align : center;  
    However, its not as simple as it sounds. Unless we define the width and line-height of the div element, this has no affect on the alignment. Define the width and line-height of the div element:
    width: 20px;  
    line-height: 20px;  
    If these values are not known beforehand, these can also be assigned in the javascript code: = myWidth + 'px'; = myHeight + 'px';