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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1667167/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 01:12:02  来源:igfitidea点击:

How do I vertical center a label in a div?

htmlcss

提问by hubert

I have a divwith a height of 30px.

我有一个div高度为30px.

I want to add plain text to this div. How can I make the plain text appear on the center of my div? i.e, the text will be shown 15pxunder the top of the div.

我想为此添加纯文本div。如何让纯文本出现在我的 div 的中心?即,文本将显示15pxdiv.

I tried a label with margin-top:15; but it didn't work.

我尝试了一个带有 margin-top:15 的标签;但它没有用。

回答by Bj?rn

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

回答by Ketan Khairnar

Following CSS would work

遵循 CSS 会起作用

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

回答by mauris

You can:

你可以:

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

Set the line-heightof the text helps you to fit the height for one line only.

设置line-height文本的 帮助您仅适合一行的高度。

回答by reko_t

Use padding-top instead of 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:

使用 padding-top 而不是 margin-top。请记住,向顶部添加填充会添加到高度,因此您需要从高度减少用于填充的量。如果您总是希望文本的顶部和底部有 15 像素,只需执行以下操作:

padding: 15px 0px;

Without specifying height at all.

完全没有指定高度。

回答by Dejan.S

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

回答by AliBZ

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". good luck

如果您希望任何东西位于其父项的中心,只需使用样式为父项指定特定宽度并为子项指定 style="margin:0 auto"。祝你好运

回答by Kieran

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>

回答by Adam

#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;
}