Search code examples
htmlcsscss-floatcentering

Is there a more efficient way to center an image inside a floated div


I was wondering if there was a more efficient way to center an image inside a floated div compared to mine. Right now I have it set up so the image is placed inside a p and I center the p. Seeing that extra p tag annoys me way too much :(. Is there anyway I can center the img by itself? Thanks! I listed what I have now down below. Edit: It needs to be vertical and horizontal!

HTML

<div class="filler"><p><img src="images/qualGraphic.png" width="578px" height="256.72px" alt="Quality"/></p></div>

CSS

.filler {
    display:table;
    width:65.6%;
    height:300px;
    background-color:#000;
    display: table;
    float:left;
}
.filler p {
    display: table-cell;
    vertical-align: middle;
    text-align: center;
}

Solution

  • To center both horizontally and vertically try adding this to the image.

    img {
      display: block;
      position: absolute;
      margin: auto;
      top:0;
      right: 0;
      bottom: 0;
      left: 0;
    }
    

    The element around the image needs to be positioned relatively i.e.

    position: relative
    

    Here's an example with an image inside a floated element

    http://jsfiddle.net/xYEuS/