简体   繁体   English

如何在 div 中垂直居中标签?

[英]How do I vertical center a label in a div?

I have a div with a height of 30px .我有一个高度为30pxdiv

I want to add plain text to this div .我想向这个div添加纯文本。 How can I make the plain text appear on the center of my div?如何让纯文本出现在我的 div 的中心? ie, the text will be shown 15px under the top of the div .即,文本将显示在div顶部下方15px

I tried a label with margin-top: 15;我尝试了一个带有margin-top: 15;的标签margin-top: 15; but it didn't work.但它没有用。

height: 30px; line-height: 30px; padding: 0;

Following CSS would work遵循 CSS 会起作用

text-align:center;
vertical-align:middle; 
display:table-cell;

You can:你可以:

<div style="height:30px; line-height:30px; text-align:center;">
    Label
</div>

Set the line-height of the text helps you to fit the height for one line only.设置文本的line-height有助于您仅适合一行的高度。

Use padding-top instead of margin-top.使用 padding-top 而不是 margin-top。 Remember that adding padding to the top is added to the height, so you need to reduce the amount that you use for padding from the height.请记住,向顶部添加填充会添加到高度,因此您需要从高度减少用于填充的量。 If you just always want for the text to have 15px on top and bottom of it, just simply do:如果您总是希望文本的顶部和底部有 15 像素,只需执行以下操作:

padding: 15px 0px;

Without specifying height at all.完全没有指定高度。

Although this is an old thread, I think a flex solution should also be presented.虽然这是一个旧线程,但我认为还应该提出一个flex解决方案。 If you style your div with如果你用你的 div 样式

display: flex; 
align-items: center;

it should work它应该工作

Codesandbox代码沙盒

padding-top: 15px;填充顶部:15px;

remove 15px from the height on the div to.从 div 上的高度删除 15px 到。

you should have a look at padding http://www.w3schools.com/css/css_padding.asp你应该看看填充http://www.w3schools.com/css/css_padding.asp

if you want anything to be in center of it's parent, just give the parent specific width using style and give the child style="margin:0 auto".如果您希望任何东西位于其父项的中心,只需使用样式为父项指定特定宽度并为子项指定 style="margin:0 auto"。 good luck祝你好运

The <label></label> Element is not a block level element it is an inline element. <label></label>元素不是块级元素,而是内联元素。

Try this code <div style="height:30px"> <label style="display:block; margin-top:15px;"> </label> </div>试试这个代码<div style="height:30px"> <label style="display:block; margin-top:15px;"> </label> </div>

#MyDiv
{ 
    background-image: url(images/pagedescription_bar.png);
    background-repeat: repeat-x;
    border-color: #868686;
    border-width: thin;
    border-style: solid;
    border-style: none;
    width: 1008px;
    height:70px;
    color: #FB8022;
    font-size: 16px;
    font-weight: bold;
}

#MyDiv label
{
    width: 1008px;
    text-align: center;
    height: 70px;
    vertical-align: middle;
    display:table-cell;
}

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

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