CSS 我怎样才能让我的文本在垂直和水平方向都出现在这个 DIV 的中心?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7453868/
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
How can I make my text appear in the center of this DIV both vetically and horizontally?
提问by Rubin
I need to center text vertically and horizontally. Is there a simple way to do this for the following code?
我需要垂直和水平居中文本。有没有一种简单的方法可以为以下代码执行此操作?
<div style="display: block; height: 25px;">
<span id="ctl_txt" style="background-color: rgb(255, 0, 0);">
Basic
</span>
</div>
回答by Jose Faeti
You can use the text-align
property to center the text horizontally, and line-height
equal to the div height to center inline elements vertically.
您可以使用该text-align
属性将文本水平居中,并line-height
等于 div 高度以垂直居中内联元素。
<div style="display: block; height: 25px; text-align:center; line-height:25px;">
<span id="ctl_txt" style="background-color: rgb(255, 0, 0);">Basic</span>
</div>
回答by Jason Gennaro
Another way to do this, different from @Jose, is to use
与@Jose 不同的另一种方法是使用
display:table;
and display:table-cell
display:table;
和 display:table-cell
like this
像这样
div{
display:table;
height:125px; //JUST FOR SHOW
width:125px; //JUST FOR SHOW
}
span{
background-color: rgb(255, 0, 0);
display:table-cell;
vertical-align:middle;
text-align:center;
}
Then vertical-align:middle;
and text-align:center;
do the work.
然后vertical-align:middle;
和text-align:center;
做的工作。