Do Not Track Me
Do Not Track Me

Reputation: 2286

Horizontally center image larger than screen & shrink image on browser resize

Hello CSS guru's of stackoverflow. I am stuck on a problem and I think perhaps it is just not possible with CSS.

I want to combine these two rules and apply them both to the same image:

1) dynamically scale image as browser size changes

#main-graphic {
    width: 100%;
    position: absolute;
    top: 0;
    left: 0;
}

2) center image and crop sides of image as browser gets smaller

#main-graphic {
  width: 2560px;
  height: 100%;
  margin-left: -1280px;
  left: 50%;
  position: relative;
}

But how do i do this with just CSS? Or is that not possible?

Upvotes: 1

Views: 1751

Answers (3)

Michael Theriot
Michael Theriot

Reputation: 1022

By setting a width in your second code block I am assuming you don't want to resize the image.

This will keep the image centered regardless of page width and crop sides if the browser width doesn't accommodate for it...

#main-graphic {
  display: inline-block;
  background-image: url('http://cux.waspdigital.com/wp-content/themes/creativeux/_/img/home-main.jpg');
  width: 100%;
  height: 228px;
  background-repeat: no-repeat;
  background-size: 1280px 228px;
  background-position: 50% 0;
}​

<div id="main-graphic"></div>​

http://jsfiddle.net/Xt2vM/

Upvotes: 0

Paulo R.
Paulo R.

Reputation: 15609

You could use the image as a background-image on an empty div for example. I'm not entirely sure of how you want it, but something like this could suit your needs.

HTML

 <div class="img"></div>

CSS

.img {
    max-width: 2560px;
    width: 100%;
    height: 100%;
    background-image: url('whatever.jpg');
    background-size: contain;
}

Upvotes: 0

danchet
danchet

Reputation: 410

You'll need to make good use of Max/Min widths (and heights).

Here is a good place to start.

Upvotes: 1

Related Questions