Center Image Vertical and Horizontal

I tend to do this every web site I design I do, but I have yet to actually find a real good way to do it. A company usually gives me their logo, I center it in the middle of the screen for when you go to the page, and then it auto forwards you to the home page. I can not seem to find a good way to center an image in the middle of the screen without a bunch of tables and divs! Any good suggestions?!


You could try using a div in your HTML like this:

<div id='dv'></div>

And using a background image like this:

#dv {
    background: url('http://pieisgood.org/images/slice.jpg') no-repeat 0 0;
    background-position: center;
}

html,body,#dv { /* so that the #dv can fill up the page */
    width:100%;
    height:100%;
}

Fiddle


Personally, I like using the display: table-cell method.

For example, if my HTML is:

<div class="wrapper">
     <img src="http://placehold.it/150x50" alt="Company ABC" />
</div>

Then my CSS should be:

div.wrapper {
    display: table-cell;
    vertical-align: middle;
    text-align: center;
    width: 600px;
    height: 200px;
}

If I'm unable to use the above method, another viable option is to use the line-height property.

HTML for line-height method:

<div class="wrapper">
    <img src="http://placehold.it/150x50" alt="Company XYZ" />
</div>

CSS for line-height method:

img {
    line-height: 300px;
}

You could use JavaScript to calculate the center point and position it with either margin or top (with position:relative/absolute), but this isn't really clean.

I'm assuming you're talking about a splash page, so here is a simple example (although in other circumstances I do not recommend modifying the body tag as I have done):

<!doctype html>
<html>
    <head>
        <title>blah</title>
        <style type="text/css">
            html,body {margin:0;padding:0;width:100%;height:100%;}
            body {display:table;}
            p {display:table-cell;text-align:center;vertical-align:middle;}
        </style>
    </head>
    <body>
        <p>Hello World - This could have an image in it</p>
    </body>
</html>

The trick is in the CSS:

  • The item you wish to center both horizontally and vertically is displayed as a table cell: display:table-cell
  • The parent (container) of the item you wish to center is displayed as a table: display:table
  • Make sure the table display element is consuming the entire area which you would like to center against.
  • The item you wish to center must be told to align horizontally ( text-align:center declaration) and vertically ( vertical-align:middle declaration)
  • The text-align and vertical-align properties only work this special way because the element is displayed as a table-cell
  • 链接地址: http://www.djcxy.com/p/7148.html

    上一篇: 元素在一个div中的垂直对齐

    下一篇: 居中图像垂直和水平