1

I have a background image which is getting scaled, but the problem is it is getting stretched and looking uglier when looked at smaller resolutions.

.bcg {
    background-position: center center;
    background-repeat: no-repeat;
    background-attachment: fixed;
    background-size: cover;
    height: 100%;
    width: 100%;
}
/* Slide 1 */
#slide-1 .bcg {background-image:url('../img/bcg_slide-1.png'); 
             background-size: 100% 100%}

HTML Markup

        <section id="slide-1" class="homeSlide">
            <div class="bcg">
                <div class="hsContainer">
                    <div class="hsContent">
                        <h2>Hello1</h2>                         
                    </div>
                </div>
            </div>
        </section>

If i use background-size: 100% auto; then its not perfectly fitting the entire window. Is there any solution to make the background-image inside a div perfect for all resolutions and sizes.

Frank
  • 179
  • 2
  • 10

2 Answers2

2

Remove the background-size from your slide, and let the .bcg class's background-size: cover work. Cover will keep the aspect ratio, and resize the image so it is the smallest it can be while still covering the entire area. Contain works similarly, but resizes it so one of the dimensions covers the entire area.

Robert McKee
  • 21,305
  • 1
  • 43
  • 57
1

background-position: contain; does work. However, you need to restructure your CSS a little in order for the percentages to work properly.

html, body, #slide-1, .bcg {
    height: 100%;
}

#slide-1 .bcg {
    background: url('http://placekitten.com/g/1600/900') top center no-repeat; 
    background-size: contain;
}

http://jsfiddle.net/CPBy2/1/


Or if you actually need the DIV to scale 16:9 so other content with flow nicely on the page, you can do that as well with a padding trick.

#content {
    position: relative;
    background: url('http://placekitten.com/g/1600/900') top center no-repeat;
    background-size: contain;
}

#content:after {
    content: "";
    display: block;
    padding-top: 56.25%;
}

<div id="content"></div>Content after

http://jsfiddle.net/46A5R/

Jason
  • 4,079
  • 4
  • 22
  • 32
  • It works, but the height is never 100% in both the cases, when i re-size – Frank Jul 31 '14 at 21:53
  • So you want a 1600x900 div scaled to fit vertically? Or do you mean the image doesn't go the top and bottom due to the default margin/padding on HTML, and BODY tags? – Jason Jul 31 '14 at 21:54
  • you want a 1600x900 div scaled to fit vertically - yes – Frank Aug 01 '14 at 06:47
  • The only way I know to scale a div vertically is with Javascript. Since padding (even top and bottom padding) is based on the width of an element, not height, scaling a div based on the vertical height doesn't work with CSS. You could use background-size: cover; that might be what you are looking for http://jsfiddle.net/CPBy2/2/ – Jason Aug 01 '14 at 14:04