My webpage contains several divs. Some are set to width: 100%, so they fill the whole page width.
But at the top of the page there is a small whitespace before the first element shows up. Moreover, that same whitespace is visible left and right from elements spanning the whole page width.
I cannot figure out why. If I set:
html, body {
width: 100%;
}
then the whitespace remains but the page is just stretched out to fit the image width of a div.
Can anyone help? It's probably pretty simple but I must be overlooking something.
Thank you.
EDIT: I must mention I'm using a parallax element. This uses a padding, so the image does fills the whole div and does not leave a black area on top. The HTML is:
<div class="js-background-1 container">
</div>
The CSS:
.container {
padding-top: 200px;
}
.js-background-1 {
background: transparent url(url/to/image) center 0 no-repeat;
}
And the javascript:
<script type="text/javascript">
var $window = $(window);
var velocity = 0.4;
function update(){
var pos = $window.scrollTop();
$('.container').each(function() {
var $element = $(this);
var height = $element.height();
$(this).css('backgroundPosition', '50% ' + Math.round((height - pos) * velocity) + 'px');
});
};
$window.bind('scroll', update);
</script>
I used the tutorial from http://www.webdesign.org/how-to-create-a-parallax-scrolling-website.22336.html, so there is where it is from. I changed the HTML a bit for my website, but the rest is the same.
I saw the comment about the margin and padding set to 0, but that leads to my div to have a blank space if you don't scroll far enough.
You must remove the margin on body:
body {
padding:0;
margin:0;
}
You can also remove padding and margin on html and body
html, body {
padding:0;
margin:0;
}
See it on jsfiddle
But I would not advise to use * (the universal selector)
* {
margin: 0px;
padding: 0px;
}
This would remove padding and margins on all elements.
The good method is to always use at the begining of the file (I forgot to metion this):
*{
margin: 0px;
padding: 0px;
}
This two line's at the begining of main CSS file fix many problem's that you can encounter.
Hope it'll help you.
padding-bottom: 20px;
border: 1px solid red !important;
margin: 0;
padding: 0;
width: 100%;
I can't seem to get my background to stay fitted to my browser when I resize the window. Please help!
Here are the images to show you what is going on: View images
The first image is how it should be fitted, the second is when I stretch it horizontally and the third is when I stretch is vertically (sorry, not sure why it uploaded my images twice)
Here is my code I am using:
body {
background: url('images/bkg-img.png');
repeat: no-repeat;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
The problem is that background-size: cover covers the background positioning area (see W3C page), which is, in some cases, the calculated height of the body. Not always as high as the window!
The simplest solution I've found is also put a
html {height:100%}
in the stylesheet. But you might have to experiment a bit with your setup to get it to work the way you want. I'm pretty sure it varies across browsers and depends on whether you're using standards or quirks mode.
There are lot's ways to do this, if you set the image as background-image of body it is not going to shrink or expand it is going to be stay same this is the expected behaviour.
You can use sth. like this for this:
<div id="bg">
<img src="images/bg.jpg" alt="">
</div>
And style of them:
#bg {
position: fixed;
top: -50%;
left: -50%;
width: 200%;
height: 200%;
}
#bg img {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
min-width: 50%;
min-height: 50%;
}
To be able to put your content above of the background image put your content inside another div like:
<div class="pagewrap">
<p>Content</p>
</div>
And class of it:
.pagewrap {
position: relative;
z-index: 2;
width: 100%;
height: 100%;
}
View demo or other techniques, about z-index.
Fixed image
If you don't need the bg image to scroll with the page, you can still apply the bg image to the body tag if you set background-attachment: fixed;
body {
background: url('images/bkg-img.png') no-repeat 0 0 fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
jQuery
If the bg image does need to scroll with the page, it might be worthwhile to apply some JavaScript or jQuery code, in the interest of keeping the HTML and CSS relatively simple.
function stretchBg(width, height, contain) {
var pageWidth = $(document).width();
var pageHeight = $(document).height();
if ((pageWidth / pageHeight) > (width / height) == !!contain)
$('body').css({backgroundSize: 'auto ' + pageHeight + 'px'});
else
$('body').css({backgroundSize: pageWidth + 'px auto'});
}
$(document).ready(function(){ stretchBg(640, 480); }); // Page load
$(window).resize(function(){ stretchBg(640, 480); }); // Browser resize
JSFiddle Demo (and standalone version of the demo)
To preserve the aspect ratio, the native width and height of the image are passed to the above function, along with an optional third parameter for whether the bg image should cover or contain the page (the default is cover).
Alternately, here's a more-advanced demo (and standalone version) that automatically detects the native resolution of the bg image currently applied to the body tag. Below is an example of using it:
$(document).ready(function(){
FullBodyBackground.init({contain: false});
});
Ok, so here's my problem.
For a client I'm using a lightbox (in this case slimbox2)
I've modified it's contents so that if the images are larger than the screensize,
the image max width/height is the screensize itself.
So in other words: if image > screensize => image == screensize
I'm using css3 background-size property for most browsers wich works just fine.
And for IE5.5+ I'm using the filter: AlphaImageLoader.
All this is good, but when I hover on the image I should get a next and previous button.
This does not work in IE7- It seems the buttons stay under the background image because
it has the css filter: AlphaImageLoader on it. Is there any way to make
the buttons visible?
Here's a piece of my code (JQUERY MERGED WITH PHP):
$bgsize = preload.width +'px '+preload.height +'px';
$(image).css({backgroundImage: "url(" + activeURL + ")",
visibility: "hidden",
display: "block",
'background-size':$bgsize,
'-webkit-background-size':$bgsize,
'filter':'progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\''+ activeURL+'\',sizingMethod=\'scale\')',
'-ms-filter':'progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\''+ activeURL+'\',sizingMethod=\'scale\'
Here's the css:
#lbImage {
position: absolute;
left: 0;
top: 0;
background-repeat: no-repeat;
}
#lbPrevLink, #lbNextLink {
display: block;
position: absolute;
top: 0;
right:-10px;
width: 50%;
outline: none;
}
#lbPrevLink {
left: 0;
}
#lbPrevLink:hover {
background: url(prevlabel.jpg) no-repeat 0 15%;
}
#lbNextLink {
right: 0;
z-index:20000;
}
#lbNextLink:hover {
background: transparent url(nextlabel.jpg) no-repeat 100% 15%;
}
PS: tried the most common solutions like z-index, positioning relative/absolute, etc..
AlphaImageLoader puts an image between the object background and content, so everything underneath is obscured. Use a background-size shim or a pure CSS lightbox as an alternative.
I would like to be able to change my webpage background image according to the screen resolution the user uses so:
if screen resolution is greater than or equal to 1200*600 then background = mybackground.jpg no-repeat or else. How can I do this?
Pure CSS approaches that work very well are discussed here. Two techniques are examined in particular and I personally prefer the second as it not CSS3 dependent, which suits my own needs better.
If most/all of your traffic has a CSS3 capable browser, the first method is quicker and cleaner to implement (copy/pasted by Mr. Zoidberg in another answer here for convenience, though I'd visit the source for further background on why it works).
An alternative method to CSS is to use the JavaScript library jQuery to detect resolution changes and adjust the image size accordingly. This article covers the jQuery technique and provides a live demo.
Supersized is a dedicated JavaScript library designed for static full screen images as well as full sized slideshows.
A good tip for full-screen images is to scale them with a correct ratio beforehand. I normally aim for a size of 1500x1000 when using supersized.js or 1680x1050 for other methods, setting the jpg quality for photographs to between 60-80% resulting in a file size in the region of 100kb or less if possible without compromising quality too much.
Delete your "body background image code" then paste this code:
html {
background: url(../img/background.jpg) no-repeat center center fixed #000;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
Hi heres a javascript version which changes the background image src according to screen resolution. You have to have the different images saved in the right size.
<html>
<head>
<title>Javascript Change Div Background Image</title>
<style type="text/css">
body {
margin:0;
width:100%;
height:100%;
}
#div1 {
background-image:url('sky.jpg');
width:100%
height:100%
}
p {
font-family:Verdana;
font-weight:bold;
font-size:11px;
}
</style>
<script language="javascript" type="text/javascript">
function changeDivImage()
{
//change the image path to a string
var imgPath = new String();
imgPath = document.getElementById("div1").style.backgroundImage;
//get screen res of customer
var custHeight=screen.height;
var custWidth=screen.width;
//if their screen width is less than or equal to 640 then use the 640 pic url
if (custWidth <= 640)
{
document.getElementById("div1").style.backgroundImage = "url(640x480.jpg)";
}
else if (custWidth <= 800)
{
document.getElementById("div1").style.backgroundImage = "url(800x600.jpg)";
}
else if (custWidth <= 1024)
{
document.getElementById("div1").style.backgroundImage = "url(1024x768.jpg)";
}
else if (custWidth <= 1280)
{
document.getElementById("div1").style.backgroundImage = "url(1280x960.jpg)";
}
else if (custWidth <= 1600)
{
document.getElementById("div1").style.backgroundImage = "url(1600x1200.jpg)";
}
else {
document.getElementById("div1").style.backgroundImage = "url(graffiti.jpg)";
}
/*if(imgPath == "url(sky.jpg)" || imgPath == "")
{
document.getElementById("div1").style.backgroundImage = "url(graffiti.jpg)";
}
else
{
document.getElementById("div1").style.backgroundImage = "url(sky.jpg)";
}*/
}
</script>
</head>
<body onload="changeDivImage()">
<div id="div1">
<p>This Javascript Example will change the background image of<br />HTML Div Tag onload using javascript screen resolution.</p>
<p>paragraph</p>
</div>
<br/>
</body>
</html>
I know it's too old question but thought to answer, it might will help someone. If you see twitter, you will find something very tricky but pure css approach to achieve this.
<div class="background"><img src="home-bg.png" /></div>
Applied CSS
.background {
background: none repeat scroll 0 0 #FFFFFF;
height: 200%;
left: -50%;
position: fixed;
width: 200%;}
.background img{
bottom: 0;
display: block;
left: 0;
margin: auto;
min-height: 50%;
min-width: 50%;
right: 0;
top: 0;}
This background images fits to all size. even portrait view of ipad. it always adjust the image in center. if you zoom out; image will remain the same.
Set body css to :
body {
background: url(../img/background.jpg) no-repeat center center fixed #000;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
I've had this same issue but have now found the resolution for it.
The trick is to create a wallpaper image of 1920*1200.
When you then apply this wallpaper to the different machines, Windows 7 automatically resizes for best fit.
Hope this helps you all
Put into css file:
html { background: url(images/bg.jpg) no-repeat center center fixed; -webkit-background-size: cover; -moz-background-size: cover; -o-background-size: cover; background-size: cover; }
URL images/bg.jpg is your background image
I need to make this image stretch to the maximum size possible without overflowing it's <div> or skewing the image.
I can't predict the aspect-ratio of the image, so there's no way to know whether to use:
<img src="url" style="width: 100%;">
or
<img src="url" style="height: 100%;">
I can't use both (i.e. style="width: 100%; height: 100%;") because that will stretch the image to fit the <div>.
The <div> has a size set by percentage of the screen, which is also unpredictable.
Update 2016:
Modern browser behave much better. All you should need to do is to set the image width to 100% (demo)
.container img {
width: 100%;
}
Since you don't know the aspect ratio, you'll have to use some scripting. Here is how I would do it with jQuery (demo):
CSS
.container {
width: 40%;
height: 40%;
background: #444;
margin: 0 auto;
}
.container img.wide {
max-width: 100%;
max-height: 100%;
height: auto;
}
.container img.tall {
max-height: 100%;
max-width: 100%;
width: auto;
}
HTML
<div class="container">
<img src="http://i48.tinypic.com/wrltuc.jpg" />
</div>
<br />
<br />
<div class="container">
<img src="http://i47.tinypic.com/i1bek8.jpg" />
</div>
Script
$(window).load(function(){
$('.container').find('img').each(function(){
var imgClass = (this.width/this.height > 1) ? 'wide' : 'tall';
$(this).addClass(imgClass);
})
})
There is a much easier way to do this using only CSS and HTML:
HTML:
<div
class="fill"
style="background-image: url('path/to/image.jpg');">
</div>
CSS:
.fill {
background-size: cover;
background-position: center;
width: 100%;
height: 100%;
}
This will place your image as the background, and stretch it to fit the div size without distortion.
Not a perfect solution, but this CSS might help. The zoom is what makes this code work, and the factor should theoretically be infinite to work ideally for small images - but 2, 4, or 8 works fine in most cases.
#myImage {
zoom: 2; //increase if you have very small images
display: block;
margin: auto;
height: auto;
max-height: 100%;
width: auto;
max-width: 100%;
}
If you're able to set the image as a background-image then you can do something like this, which will crop the image without stretching it:
<div style="background-image: url(...); background-size: cover; width: 100%; height: 100%;"></div>
If you need to stick with an <img> tag, then as of 2019, you can now use the object-fit css property that accepts the following values:
fill | contain | cover | none | scale-down
See https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit
As an example, you could have a container that holds an image:
<div class="container">
<img src="" class="container_img" />
</div>
.container {
height: 50px;
width: 50%;
}
.container_img {
height: 100%;
width: 100%;
object-fit: cover;
}
If you can, use background images and set background-size: cover. This will make the background cover the whole element.
CSS
div {
background-image: url(path/to/your/image.png);
background-repeat: no-repeat;
background-position: 50% 50%;
background-size: cover;
}
If you're stuck with using inline images there are a few options. First, there is
object-fit
This property acts on images, videos and other objects similar to background-size: cover.
CSS
img {
object-fit: cover;
}
Sadly, browser support is not that great with IE up to version 11 not supporting it at all. The next option uses jQuery
CSS + jQuery
HTML
<div>
<img src="image.png" class="cover-image">
</div>
CSS
div {
height: 8em;
width: 15em;
}
Custom jQuery plugin
(function ($) {
$.fn.coverImage = function(contain) {
this.each(function() {
var $this = $(this),
src = $this.get(0).src,
$wrapper = $this.parent();
if (contain) {
$wrapper.css({
'background': 'url(' + src + ') 50% 50%/contain no-repeat'
});
} else {
$wrapper.css({
'background': 'url(' + src + ') 50% 50%/cover no-repeat'
});
}
$this.remove();
});
return this;
};
})(jQuery);
Use the plugin like this
jQuery('.cover-image').coverImage();
It will take an image, set it as a background image on the image's wrapper element and remove the img tag from the document. Lastly you could use
Pure CSS
You might use this as a fallback. The image will scale up to cover it's container but it won't scale down.
CSS
div {
height: 8em;
width: 15em;
overflow: hidden;
}
div img {
min-height: 100%;
min-width: 100%;
width: auto;
height: auto;
max-width: none;
max-height: none;
display: block;
position: relative;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
Hope this might help somebody, happy coding!
Thanks to CSS3
img
{
object-fit: contain;
}
https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit
IE and EDGE as always outsiders:
http://caniuse.com/#feat=object-fit
That's impossible with just HTML and CSS, or at least wildly exotic and complicated. If you're willing to throw some javascript in, here's a solution using jQuery:
$(function() {
$(window).resize(function() {
var $i = $('img#image_to_resize');
var $c = $img.parent();
var i_ar = $i.width() / $i.height(), c_ar = $c.width() / $c.height();
$i.width(i_ar > c_ar ? $c.width() : $c.height() * (i_ar));
});
$(window).resize();
});
That will resize the image so that it will always fit inside the parent element, regardless of it's size. And as it's binded to the $(window).resize() event, when user resizes the window, the image will adjust.
This does not try to center the image in the container, that would be possible but I guess that's not what you're after.
You can use object-fit: cover; on the parent div.
https://css-tricks.com/almanac/properties/o/object-fit/
Set width and height of the outer container div. Then use below styling on img:
.container img{
width:100%;
height:auto;
max-height:100%;
}
This will help you to keep an aspect ratio of your img
If you want to set a max width or height (so that it will not be very large) while keeping the images aspect-ratio, you can do this:
img{
object-fit: contain;
max-height: 70px;
}
I came across this question searching for a simular problem. I'm making a webpage with responsive design and the width of elements placed on the page is set to a percent of the screen width. The height is set with a vw value.
Since I'm adding posts with PHP and a database backend, pure CSS was out of the question. I did however find the jQuery/javascript solution a bit troblesome, so I came up with a neat (so I think myself at least) solution.
HTML (or php)
div.imgfill {
float: left;
position: relative;
background-repeat: no-repeat;
background-position: 50% 50%;
background-size: cover;
width: 33.333%;
height: 18vw;
border: 1px solid black; /*frame of the image*/
margin: -1px;
}
<div class="imgfill" style="background-image:url(source/image.jpg);">
This might be some info
</div>
<div class="imgfill" style="background-image:url(source/image2.jpg);">
This might be some info
</div>
<div class="imgfill" style="background-image:url(source/image3.jpg);">
This might be some info
</div>
By using style="" it's posible to have PHP update my page dynamically and the CSS-styling together with style="" will end up in a perfectly covered image, scaled to cover the dynamic div-tag.
To make this image stretch to the maximum size possible without overflowing it's or skewing the image.
Apply...
img {
object-fit: cover;
height: -webkit-fill-available;
}
styles to the image.
Using this method you can fill in your div with the image varying ratio of divs and images.
jQuery:
$(window).load(function(){
$('body').find(.fillme).each(function(){
var fillmeval = $(this).width()/$(this).height();
var imgval = $this.children('img').width()/$this.children('img').height();
var imgClass;
if(imgval > fillmeval){
imgClass = "stretchy";
}else{
imgClass = "stretchx";
}
$(this).children('img').addClass(imgClass);
});
});
HTML:
<div class="fillme">
<img src="../images/myimg.jpg" />
</div>
CSS:
.fillme{
overflow:hidden;
}
.fillme img.stretchx{
height:auto;
width:100%;
}
.fillme img.stretchy{
height:100%;
width:auto;
}
This did the trick for me
div img {
width: 100%;
min-height: 500px;
width: 100vw;
height: 100vh;
object-fit: cover;
}
if you working with IMG tag, it's easy.
I made this:
<style>
#pic{
height: 400px;
width: 400px;
}
#pic img{
height: 225px;
position: relative;
margin: 0 auto;
}
</style>
<div id="pic"><img src="images/menu.png"></div>
$(document).ready(function(){
$('#pic img').attr({ 'style':'height:25%; display:none; left:100px; top:100px;' })
)}
but i didn't find how to make it work with #pic { background:url(img/menu.png)}
Enyone?
Thanks
I had similar issue. I resolved it with just CSS.
Basically Object-fit: cover helps you achieve the task of maintaining the aspect ratio while positioning an image inside a div.
But the problem was Object-fit: cover was not working in IE and it was taking 100% width and 100% height and aspect ratio was distorted. In other words image zooming effect wasn't there which I was seeing in chrome.
The approach I took was to position the image inside the container with absolute and then place it right at the centre using the combination:
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
Once it is in the centre, I give to the image,
// For vertical blocks (i.e., where height is greater than width)
height: 100%;
width: auto;
// For Horizontal blocks (i.e., where width is greater than height)
height: auto;
width: 100%;
This makes the image get the effect of Object-fit:cover.
Here is a demonstration of the above logic.
https://jsfiddle.net/furqan_694/s3xLe1gp/
This logic works in all browsers.
HTML:
<style>
#foo, #bar{
width: 50px; /* use any width or height */
height: 50px;
background-position: center center;
background-repeat: no-repeat;
background-size: cover;
}
</style>
<div id="foo" style="background-image: url('path/to/image1.png');">
<div id="bar" style="background-image: url('path/to/image2.png');">
JSFiddle
...And if you want to set or change the image (using #foo as an example):
jQuery:
$("#foo").css("background-image", "url('path/to/image.png')");
JavaScript:
document.getElementById("foo").style.backgroundImage = "url('path/to/image.png')";
Many of the solutions found here have some limitation: some not working in IE ( object-fit) or older browsers, other solutions do not scale up the images (only shrink it), many solution do not support resize of the window and many are not generic, either expect fix resolution or layout(portrait or landscape)
If using javascript and jquery is not a problem I have this solution based on the code of #Tatu Ulmanen. I fixed some issues, and added some code in case the image is loaded dinamically and not available at begining. Basically the idea is to have two different css rules and apply them when required: one when the limitation is the height, so we need to show black bars at the sides, and othe css rule when the limitation is the width, so we need to show black bars at the top/bottom.
function applyResizeCSS(){
var $i = $('img#imageToResize');
var $c = $i.parent();
var i_ar = Oriwidth / Oriheight, c_ar = $c.width() / $c.height();
if(i_ar > c_ar){
$i.css( "width","100%");
$i.css( "height","auto");
}else{
$i.css( "height","100%");
$i.css( "width","auto");
}
}
var Oriwidth,Oriheight;
$(function() {
$(window).resize(function() {
applyResizeCSS();
});
$("#slide").load(function(){
Oriwidth = this.width,
Oriheight = this.height;
applyResizeCSS();
});
$(window).resize();
});
For an HTML element like:
<img src="images/loading.gif" name="imageToResize" id="imageToResize"/>
try this
HTML:
<div class="container"></div>
CSS:
.container{
background-image: url("...");
background-size: 100%;
background-position: center;
}