Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

CSS

Resizing div automatically depending on screen size

Hi, I am trying to build a web page with an image that fills the screen and re-sizes to the same percentage when the height is changed.

Here is an example: http://davidhellmann.com/

The main image at the top re-sizes when the height of the browser is changed.

Any ideas?

Becky Castle
Becky Castle
15,294 Points

Hi Liam, You could make a div that is 100% wide, by maybe 66.67vh high (if you were to mimick your example), and who's background image covers the whole div. Thus, when you resize the browser, your image will always fill 100% the width of the screen and 2/3 the height (or whatever height you choose). So, the css for that would look like:

div {
    width:100%;
    height:66.67vh;
    background:url('your_image.jpg') no-repeat center center;
    background-size:cover;
    overflow:hidden;
}

Thank you both, that has worked nicely. The vh units were a great suggestion.

2 Answers

Becky Castle
Becky Castle
15,294 Points

I'm glad you have it figured out! Just a head's up about the vh (and vw) units: although they're super awesome to use for setting responsive widths & heights, I've noticed that there's a glitch when viewed in Safari. So, if you're working on a legit site, you might want to check out this viewport buggy fill. Simply add the .js file to your ftp, and add the given link <script src="viewport-units-buggyfill.js"></script> <script>window.viewportUnitsBuggyfill.init();</script> in the bottom of your html file.

Kevin Korte
Kevin Korte
28,148 Points

To build on what Becky Castle said, there are some minor issues with mostly IE and VH.

Check this out. Notes at the bottom: http://caniuse.com/#search=vh

But yes, VH units are pretty awesome.

Shaker Advertising
Shaker Advertising
5,395 Points

You can use background size cover and set the background to the appropriate origin. This will cover the full space of the div with the background image no matter what size the div is.

.wrapper{
    background: url(PATH_TO_MY_IMAGE) bottom center no-repeat #ffffff;
    background-size:cover;
}