William Smith
William Smith

Reputation: 852

CSS positioning- vertically centered w/out losing top of image in smaller window

I'm using this CSS to vertically center a sprite:

#content {
    width:750px;
    height:950px;
    position:absolute;
    left:50%;
    top:50%;
    margin:-475px 0 0 -375px;
}

...when the height of the browser window is less than 950px I lose the top of my image. How could I set the image to center vertically when the browser height is greater than 950px, but when it's less, the top of the image remains fixed and I only lose the bottom part?

I'm already using links in my source code to switch between css style sheets based on screen size such as this:

<link rel="stylesheet" media="screen and (min-width:481px) and (max-width:800px)"
href="tablet.css" />

but as I understand it, you can't switch style sheets based in browser height.

Upvotes: 3

Views: 140

Answers (1)

insertusernamehere
insertusernamehere

Reputation: 23590

The most simple way to center the image vertically (and in the example also horizontally) could be this approach:

  • centers the image as long as the screen is bigger than the image
  • places it on top as soon as the image gets smaller than the screen

Hope this is the behavior you'd expected

DEMO

http://jsfiddle.net/uB3pW/

HTML

<div class="wrapper">
    <img class="sprite" src="http://lorempixel.com/output/nightlife-q-c-750-500-4.jpg" alt="">
</div>

CSS

* {
    margin:     0;
    padding:    0;
}

body, html {
    display:    table;
    width:      100%;
    height:     100%;
}

div.wrapper {
    display:    table-cell;
    position:   relative;
    top:        0px;
    left:       0px;
    width:      100%;
    height:     100%;
    background: #ccc;
    text-align: center;
    vertical-align: middle;
}

Note

Won't work in IE7.

Upvotes: 2

Related Questions