Why can't a choose a fixed height for my wrapper without affecting vertical alignment of children?

StackOverflow https://stackoverflow.com/questions/22162029

  •  19-10-2022
  •  | 
  •  

Pergunta

This has been bothering me. Although I've resolved my problem using padding for the container to create the desired height of the container, I'm still puzzled on why this happens.

I have a container with two child elements inside, like so:

<div class="container">
    <img src="http://placehold.it/30x30" id="first-item"/>
    <img src="http://placehold.it/50x50" id="second-item"/>
</div>

I vertical align the children to the container using the below:

#first-item, #second-item {
    display: inline-block;
    vertical-align: middle;
 }

However, if a fixed height is set for the container, the vertical alignment breaks.

Why is this so?

http://jsfiddle.net/Nx8Jc/

Foi útil?

Solução

It will work if you add a line-height property with an identical value to the height:

.container {
    background-color: #EADDBB;
    height: 100px; 
    line-height: 100px;
    width: 100%;
    padding: 20px 20px;
}

#first-item, #second-item {
    display: inline-block;
    vertical-align: middle;
}

Demo: http://jsfiddle.net/galengidman/Nx8Jc/1/

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top