简体   繁体   English

将文本左对齐并垂直居中于div

[英]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). 我有这个JS代码,我用它来创建一个新的div(我动态创建几个)。 I want my text to be in the centered vertically and aligned to the left side of the div. 我希望我的文本垂直居中并与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. 此代码将文本水平居中,它似乎倾向于div的顶部而不是中间。

If the height of div is constant (seems like it is 70px) than you can use line-height: 70px; 如果div的高度是常数(看起来像是70px),那么你可以使用line-height: 70px; to render any text vertically centered. 渲染任何文本垂直居中。

<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. 设置margin-top:-yy ,其中yy是子容器高度的一半,以抵消项目。

Source : http://www.vanseodesign.com/css/vertical-centering/ 资料来源: http//www.vanseodesign.com/css/vertical-centering/

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. 不能将div内的文本垂直对齐而不使其成为表格单元格,或者你必须在div中插入一个跨度并给它50%的高度。

Check below code. 检查以下代码。

http://jsbin.com/agekuq/edit#preview 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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM