Question

I need to vertical align a span, but the thing that makes this complicated is that this span needs to occupy its whole parent. Something like this jsfiddle

So, the HTML is

<div>
    <span>OK</span>
</div>

CSS:

div {
     width: 200px;
     height: 200px;
     background-color: lightgrey;
}

span {
    display: block;
    width: 100%;
    height: 100%;
    vertical-align: middle;
}

Is this possible without changing the html ?

UPDATE: Although the below answers are all correct and interesting, I chose the one I actually used to be the correct one!

Was it helpful?

Solution

Tell it to behave like a table:

div {
    width: 200px;
    height: 200px;
    background-color: lightgrey;
    display: table;
}
span {
    display: table-cell;
    text-align: center;
    vertical-align: middle;
}

http://jsfiddle.net/9uaE6/2/

OTHER TIPS

div{ 
/* Internet Explorer 10 */
display:-ms-flexbox;
-ms-flex-pack:start;
-ms-flex-align:center;

/* Firefox */
display:-moz-box;
-moz-box-pack:start;
-moz-box-align:center;

/* Safari, Opera, and Chrome */
display:-webkit-box;
-webkit-box-pack:start;
-webkit-box-align:center;

/* W3C */
display:box;
box-pack:start;
box-align:center; 
}

Source:ms-flex

your Updated Fiddle

You could achieve that with a 'ghost' pseudo element

span {
    display: block;
    width: 100%;
    height: 100%;
    vertical-align: middle;
    text-align: center;
}

span:before {
    content: "";
    display:inline-block;
    vertical-align: middle;
    height: 100%;
}

An example : http://jsfiddle.net/9uaE6/11/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top