-1

I have a div in body:

<div class="wrapper" style="position: fixed">
    <img src="#">
</div>

The <img> has its intrinsic width and height (and unknown). So how do I do to center the <div> in srceen (by CSS, not Jquery or Javascript)?

Marc Audet
  • 46,011
  • 11
  • 63
  • 83
nhansay
  • 29
  • 1
  • 6

2 Answers2

2

Demo

css

img {
    position:fixed;
    top:0;
    bottom:0;
    left:0;
    right:0;
    margin:auto;
    background: #000;
}
4dgaurav
  • 11,360
  • 4
  • 32
  • 59
0

I suppose you want the .wrapper to have a fixed position because you want to have it as a header or footer. This makes it wrap to its contents, so you need to explicitly tell it to stretch to 100% width. Next, img are displayed inline. Therefore, to use the auto margin trick, you need to set its display to block:

.wrapper {
    position: fixed;
    width: 100%;
    background: lightblue;
}
img {
    display: block;
    margin: 0 auto;
}

Working jsfiddle here: http://jsfiddle.net/7swkv/

Daze
  • 478
  • 5
  • 17