nsilva
nsilva

Reputation: 5612

How can I crop a background image horizontally and retain height on browser resize?

Here is my code:-

HTML

<div id="header-main"></div>

CSS

#header-main {
    background: url(http://planetbounce.m360.co.uk/wp-content/themes/planetbounce/assets/img/planet-bg.jpg);
    background-position: center;
    background-size: 100%;
    background-repeat: no-repeat;
    width: 100%;
    height: 1075px;
    position: relative;
    display: block;
    transition: background-size 300ms ease-in;
    -moz-transition: background-size 300ms ease-in;
    -web-kit-transition: background-size 300ms ease-in;
    background-position-y: 22%;
}

JSFIDDLE HERE

On resizing the browser I need to retain the height of the image so that it essentially crops the left and right side as the browser reduces in size.

I have tried the following:-

background-size: auto 100%;

But this messes up the animation in Safari which you can see here.

I have also tried using background-size: cover; but as far as I can see there is no way to animate a background from say '93% to cover' so I can't use this either.

Any other ways I can achieve this?

Upvotes: 1

Views: 84

Answers (1)

bencodezen
bencodezen

Reputation: 1063

You're really close! The reason the height is resizing is because you have defined the background-size with 100% which causes it to keep the ratio as you resize the browser.

If you remove that line, you should see it work as desired.

Here's a demo of it.

http://codepen.io/BenCodeZen/pen/jqKMYz?editors=1100

Let me know if you have any questions!

Upvotes: 1

Related Questions