hubert
hubert

Reputation: 273

How do I vertical center a label in a div?

I have a div with a height of 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 15px under the top of the div.

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

Upvotes: 25

Views: 72472

Answers (9)

Apostolos
Apostolos

Reputation: 10463

Although this is an old thread, I think a flex solution should also be presented. If you style your div with

display: flex; 
align-items: center;

it should work

Codesandbox

Upvotes: 6

mauris
mauris

Reputation: 43619

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.

Upvotes: 13

Adam
Adam

Reputation: 459

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

Upvotes: 0

Ketan Khairnar
Ketan Khairnar

Reputation: 1630

Following CSS would work

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

Upvotes: 16

Kieran
Kieran

Reputation: 18059

The <label></label> Element is not a block level element it is an inline element.

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

Upvotes: 0

AliBZ
AliBZ

Reputation: 4099

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

Upvotes: 0

Bj&#246;rn
Bj&#246;rn

Reputation: 29411

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

Upvotes: 28

Dejan.S
Dejan.S

Reputation: 19158

padding-top: 15px;

remove 15px from the height on the div to.

you should have a look at padding http://www.w3schools.com/css/css_padding.asp

Upvotes: 0

reko_t
reko_t

Reputation: 56440

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: 15px 0px;

Without specifying height at all.

Upvotes: 1

Related Questions