我有一个div设置显示:块(90px高和宽),我有一些文本在里面。

我需要文本在中心垂直和水平对齐。

我已经尝试了text-align:center,但它不做垂直居中部分,所以我尝试了vertical-align:middle,但它不起作用。

什么好主意吗?


当前回答

将这个CSS类赋给目标<div>:

.centered { 宽度:150 px; 身高:150 px; 显示:flex; 对齐项目:中心; justify-content:中心; text-align:中心; 背景:红色;/*不需要只是为了清楚地看到结果*/ } <div class="居中">这个文本水平和垂直居中</div>

其他回答

添加行显示:table-cell;到该div的CSS内容。

只有表格单元格支持vertical-align: middle;,但是你可以把[table-cell]定义给div…

一个活生生的例子在这里:http://jsfiddle.net/tH2cc/

div{
    height: 90px;
    width: 90px;
    text-align: center;
    border: 1px solid silver;
    display: table-cell; /* This says treat this element like a table cell */
    vertical-align:middle; /* Now we can center vertically like in a TD */
}

将这个CSS类赋给目标<div>:

.centered { 宽度:150 px; 身高:150 px; 显示:flex; 对齐项目:中心; justify-content:中心; text-align:中心; 背景:红色;/*不需要只是为了清楚地看到结果*/ } <div class="居中">这个文本水平和垂直居中</div>

您可以尝试以下方法:

If you have a single word or one line sentence, then the following code can do the trick. Have a text inside a div tag and give it an id. Define the following properties for that id. id-name { height: 90px; line-height: 90px; text-align: center; border: 2px dashed red; } Note: Make sure the line-height property is same as the height of the division. Image But, if the content is more than one single word or a line then this doesn’t work. Also, there will be times when you cannot specify the size of a division in px or % (when the division is really small and you want the content to be exactly in the middle). To solve this issue, we can try the following combination of properties. id-name { display: flex; justify-content: center; align-items: center; border: 2px dashed red; } Image These 3 lines of code sets the content exactly in the middle of a division (irrespective of the size of the display). The "align-items: center" helps in vertical centering while "justify-content: center" will make it horizontally centered. Note: Flex does not work in all browsers. Make sure you add appropriate vendor prefixes for additional browser support.

这是非常简单的代码,为我工作!它只有一行,你的文本将水平居中。

.center-horizontally{
  justify-content: center;
}
<Card.Footer className="card-body-padding center-horizontally">
  <label className="support-expand-text-light">Call or email Customer Support to change</label>
</Card.Footer>

输出如下所示:

方法1

div { 身高:90 px; 行高:90 px; text-align:中心; 边界:2px虚线#f69c55; } < div > 你好,世界! ! < / div >

方法2

div { 身高:200 px; 行高:200 px; text-align:中心; 边界:2px虚线#f69c55; } 跨度{ 显示:inline-block; vertical-align:中间; 行高:正常; } < div > <span>我与你同在,我与你同在。对我说,对我说,对我说。非enim iam stirpis bonum quaeret, sed animalis。< / span > < / div >

方法3

div { 显示:表; 身高:100 px; 宽度:100%; text-align:中心; 边界:2px虚线#f69c55; } 跨度{ 显示:表格单元; vertical-align:中间; } < div > <span>神圣的神圣,神圣的神圣。</span> < / div >