javascript 在div中将文本左对齐并垂直居中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9629312/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Align Text to Left and Vertically Center in div
提问by mkyong
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:
我有这个 JS 代码,我用它来创建一个新的 div(我动态地创建了几个)。我希望我的文本垂直居中并与 div 的左侧对齐。关于该怎么做的任何建议?这是我的代码:
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 的顶部而不是中间。
回答by Ekin Koc
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.
如果 div 的高度是恒定的(似乎是 70 像素),那么您可以line-height: 70px;
用来呈现垂直居中的任何文本。
回答by Vrushank
<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/
回答by Praveen Vijayan
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>