mkyong
mkyong

Reputation: 12947

Align Text to Left and Vertically Center in div

I have this JS code that I use to create a new div (I create several, dynamically). I want my text to be in the centered vertically and aligned to the left side of the div. Any suggestions on what to do? Here is my code:

        var leftDiv = document.createElement("div"); //Create left div
        leftDiv.id = "left"; //Assign div id
        leftDiv.setAttribute("style", "float:left;width:70%;vertical-align:middle; height:26px;"); //Set div attributes
        leftDiv.style.background = "#FFFFFF";
        leftDiv.style.height = 70; 
        user_name = document.createTextNode(fullName + ' '); //Set user name

One other thing. This code will center the text horizontally and it seems to gravitate to the top of the div instead of the middle.

Upvotes: 1

Views: 17734

Answers (3)

Praveen Vijayan
Praveen Vijayan

Reputation: 6761

It is not possible to vertical align text inside div with out making it table cell, or you have to insert a span inside div & give it 50% height.

Check below code.

http://jsbin.com/agekuq/edit#preview

  <div
    id="left"
    style="background:red;
           display:table-cell;
           width:150px;
           height:150px;
           vertical-align:middle;"
  > My full name</div>

Upvotes: 0

Vrushank
Vrushank

Reputation: 2813

<style type="text/css">
   #myoutercontainer { position:relative }
   #myinnercontainer { position:absolute; top:50%; height:10em; margin-top:-5em }
</style>

...
...

<div id="myoutercontainer">
   <div id="myinnercontainer">
      <p>Hey look! I'm vertically centered!</p>
      <p>How sweet is this?!</p>
   </div>
</div>

Set margin-top:-yy where yy is half the height of the child container to offset the item up.

Source : http://www.vanseodesign.com/css/vertical-centering/

Upvotes: 1

Ekin Koc
Ekin Koc

Reputation: 2997

If the height of div is constant (seems like it is 70px) than you can use line-height: 70px; to render any text vertically centered.

Upvotes: 5

Related Questions