Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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,135 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;
}