Try to use:
$(window).resize(function() {
$('#hero').height($(window).height());
}).resize();
سؤال
I was wondering how I can fill a hero image to the browser viewport. So that the height of the hero section is always the height of the viewport.
I came up with the following piece of code, but it isn't working:
function resizer() {
var fulls = $('#hero');
console.log(fulls);
var win = $(window);
resize.on(function() {
fulls.height(win.height());
});
};
المحلول 3
Try to use:
$(window).resize(function() {
$('#hero').height($(window).height());
}).resize();
نصائح أخرى
Simply, use the viewport width and height:
fulls.style.height = "100vh"; //which means 100% of the viewport height, same works for width
It will be a good idea to set the viewport meta tag:
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
Try this code here http://jsfiddle.net/F7AN5/2/
HTML:
<div id="hero">
<img src="http://www.thememorist.com/wp-content/uploads/2012/03/superhero-blank1.jpg" alt=""/>
</div>
CSS:
body{
padding:0;
margin:0;
}
img{
display:block;
}
jQuery
$(document).ready(function(){
var resizeHero = function()
{
var hero = $("#hero"), window1 = $(window);
hero.css({
"width": window1.width(),
"height": window1.height()
});
if(window1.width() < window1.height())
{
hero.find("img").css({
"width": window1.width(),
"height": "auto"
});
}
else
{
hero.find("img").css({
"height": window1.height(),
"width": "auto"
});
}
};
resizeHero();
$(window).resize(function(){
resizeHero();
});
});
JS-free solution. Haven't tested, but should work in theory.
Assuming the markup is...
<div id="hero">
<img src="http://www.thememorist.com/wp-content/uploads/2012/03/superhero-blank1.jpg" alt=""/>
</div>
Then it could use the object-fit
style, which only requires the parent to have a height...
#hero {height: 100vh; width: 100vw; }
#hero img { object-fit: cover; }
The object fit size works like newer background-image sizes: cover | contain | fit | 100% | etc