Вопрос

I need to have an image centered with respect to the top of the div and the sides of the div. In other words, the amount of space between the left edge of the div and the left edge of the image must be the same as the amount of space on the opposite side. Same is true for the top edge of the div and the top edge of the image. I looked at the following code from this question and have this (almost identical except for the classes being ids).

CSS:

#img_holder {
    background-color:#EC0610;
    height: 500px;
    float:left;
    width: 550px;
    text-align: center;
}

#vertical_center {
    display: inline-block;
    height: 100%;
    vertical-align: middle;
}    

#image {
    vertical-align: middle;
    max-height: 500px;
    max-width: 550px;
}

HTML:

<div id="img_container">

  <div id="left_ctrl">

      Left control buttons

  </div>

  <div id="img_holder">

      <div id="vertical_center">

           <!-- Image inserted by javascript but the resulting html is this --> 
           <img id="image" src="../../images/bball1.jpg />

      </div>

  </div>

  <div id="right_ctrl">

      Right control buttons

  </div>

</div>

My image appears centered horizontally, but not vertically. Any ideas as to why? Browser is Chromium 32 running on Arch Linux.

Это было полезно?

Решение 2

Well, considering this approach, you've made a mistake in your markup. The image shouldn't be nested in the #vertical_center element. In other words, the #image and #vertical_center elements should be siblings, as follows:

<div id="img_holder">
    <div id="vertical_center"></div>
    <img id="image" src="http://placehold.it/200" />        
</div>

UPDATED DEMO.

Also, there would be a white space character between two inline-block elements. You could remove that by setting the font-size of their parent to 0 (or using an image replacement technique):

#img_holder {
    font: 0/0 a;
    /* other styles... */
}

Другие советы

HTML:

<div id="img_holder">
    <img id="image" src="http://placehold.it/300x300">
</div>

CSS:

#img_holder {
    background-color:#EC0610;
    height: 500px;
    width: 550px;
    position: relative;
}

#image {
   position: absolute;
   top: 50%;
   left: 50%;
   width: 300px;
   height: 300px;
   margin-top: -150px; /* Half the height */
   margin-left: -150px; /* Half the width */
}

DEMO: JSFIDDLE

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top