Using JS/JQuery how can I automatically change an image width/height based on a background DIV tag or window ?
You can use jQuery's width() function both to determine the width of the window and/or div, and also to assign the image's width:
var windowWidth = $(window).width();
$('img').width(windowWidth);
<div id="background-div">
<img src="xxxx.jpg" width="100%" height="100%"/>
</div>
For dynamic height you should see jQuery.height()
Using javascript you can change the height dynamically using this
var windowHeight = document.getElementsByTagName('body')[0].clientHeight;
document.getElementById("background-div").height = windowHeight + "px";
or
document.getElementById("background-div").style.height = windowHeight + "px";
For this you can use the jquery width() and height() methods or using css just specify the following rule.
img{ max-width:100%;}
Note that, this will set the dimensions of the image based on its parent div dimensions.
Have a look here http://www.cssplay.co.uk/layouts/background.html
It's a demo how to display and image with 100% width as a background .
I would use css for this.
CSS
.bg-Image {
background-image: url();
background-size: contain;
background-position: 50% 50%;
background-repeat: no-repeat;
background-attachment: scroll;
background-color: transparent;
width: desiredWidth;
height: desiredHeight;
}
HTML
<div class="bg-Image"></div>
Now you could even use jquery to dynamically change the background-image, width & height of the div.
background-size: contain;
does the trick.
But it is a css3 property. It will not work in <= ie8.
Related
Is there a way that css/html5 can fit an image optimally to a viewport such that no cropping will occur?
I would appreciate a solution above. Here's how it might be done in code:
If the aspect ratio of the image (H/W) is larger than the display, then the image css would be height:100%, width:auto;
If the aspect ratio of the image (H/W) is smaller than the display, then the image css would be height:auto, width:100%
This seems like a lot of work, is there a simpler solution?
Sam
Try this and see if it works for you. the vh unit means viewport height.
.that-image {
display: block;
height: 100vh;
position: absolute;
}
There is a corresponding unit for width, vw.
You can set is as your div background and give this styles
<div class='my-image.jpg'></div>
.my-image {
background-repeat: no-repeat;
background-position: center;
background-size: cover;
text-align: center;
height: 100vh;
width: 100vw;
background-image: url("https://images.pexels.com/photos/457882/pexels-photo-457882.jpeg");
}
Here's what I went with to avoid distorting the image aspect ratio:
function fitImage() { // Optimally fit an image to the viewport
var width = $(this).width(); // Current image width
var height = $(this).height(); // Current image height
var viewportHeight = $(window).height(); // The viewport height/width
var viewportWidth = $(window).width();
var aspectImage = parseFloat(height)/parseFloat(width); // Need Floating point
var aspectViewport = parseFloat(viewportHeight)/parseFloat(viewportWidth);
if (aspectImage > aspectViewport) { // height:100%;width:auto;
$(this).width("auto"); // Image aspect ratio > Viewport
$(this).height("100%");
} else { // height:auto;width:100%
$(this).width("100%"); // Image aspect ration <= Viewport
$(this).height("auto");
}
}
What I am trying to do is center an image using this bit of jQuery. The selector for my image is " .section-header img ".
var image_center = function(){
var imageWidth = $('.section-header img').width();
var windowWidth = $(window).width();
var centerFix = -(imageWidth-windowWidth)/2 ;
console.log(imageWidth, windowWidth, centerFix);
$('.section-header img').css({'left': centerFix});
}
I call the function when the document is ready and when the window is resized:
$(document).ready(function(){
image_center();
$(window)resize(function(){
image_center();
}
My problem is that I cannot get the function to work when the window initially loads. Looking in my console, the browser reads the image as having the same width as the browser. Once I resize the browser, the actual width of the image is read. Is there something built into Chrome that is tripping me up here? Is there an easier way to do this (without using background-image)??
Thank you,
CPR
It would probably be easier to use css for this job.
.section-header {
background-image: url("/path/to/image.jpg");
background-position: center;
background-size: contain;
background-repeat: no-repeat;
}
Not sure if you also want the img to resize.
Here is an example with resize and your img tag + section-header div or whatever it is:
.section-header{
width: 50%;
left: 25%;
margin-left: auto;
position: absolute;
}
img{
width: 100%;
height: 100%;
}
<div class="section-header">
<img src="http://placehold.it/350x150" alt="">
</div>
https://jsfiddle.net/Lj4mfqLa/
UPDATE:
You could also try to wrap your jquery code in:
$(window).load(function(){
//initialize after images are loaded
});
instead of
$(document).ready(function(){})
What I am trying to do is get the height of the screen and the width of the screen and then use the document.getElement.style.property = newStyle to change the style to the obtained height of the screen and width of the screen. I tried making the height and width into Strings to use, I also tried putting just the values in. I want to know how to put in px values and % values. Thanks.
<!DOCTYPE html>
<html lang = "en/US">
<head>
<title>
cyclebg test
</title>
<style>
body {
background: url("http://i.dailymail.co.uk/i/pix/2016/03/22/13/32738A6E00000578-3504412-image-a-6_1458654517341.jpg")
no-repeat;
background-position: center top;
background-size: 200px 100px;
}
p {
padding: 50px; background-color: green; margin-left: -1%; margin-right: -1%; display: block;
}
</style>
</head>
<body>
<p style = "margin-top: 25%;"> Hello World </p>
<p> Yo </p>
</body>
<script>
var heightOfScreen = screen.height;
var widthOfScreen = screen.width;
var heightOfScreenString = heightOfScreen + " px";
var widthOfScreenString = widthOfScreen + " px";
document.getElementsByTagName("body")[0].style.backgroundSize = "heightOfScreenString widthOfScreenString";
</script>
</html>
You should try using
background-size: cover;
So the background will cover the whole size of the background and cropoff the excess.
If you want the full background to show (despite of blank spaces on top or sides) you can use "contain" instead
https://jsfiddle.net/0vps9x0s/
This shortest & simplest answer is to use CSS to cover the background image and crop the excess, using this:
background-size: cover;
If you want to "fit" the background image to the container, use this:
background-size: 100% 100%;
If you want use jQuery to get the width & height of the window and set the size of the background image, do this:
var width = $(window).width();
var height = $(window).height();
// NOTE: this does the same thing as "background-size: 100% 100%;"
$("body").css("background-size", width + "px " + height + "px");
If you just want to use Vanilla JavaScript to get the width & height of the window and set the size of the background image, use this:
var width = window.innerWidth;
var height = window.innerHeight;
// NOTE: this does the same thing as "background-size: 100% 100%;"
document.getElementsByTagName("body")[0].style.backgroundSize = width + "px " + height + "px";
Good luck and all the best.
I'm trying to fit my 'body' background image to the browsers document size.
This code here doesn't change anything in browser when i run it... i see the image but it is repeated twice and the size isn't changing. when debugging i see that the width and height variables are correct but nothing actually happens.... any ideas?
$(function() { // onload...do
var width = $(document).width();
var height = $(document).height();
$('body').css.backgroundSize = "" + width + "px " + height + "px";
});
body{
background: url(../images/MainMenuScreen.jpg);
}
Try this:
#yourdiv /* with CSS 3 */
{
background: url(../images/MainMenuScreen.jpg) no-repeat;
background-size: 100%;
}
You can use the background-size:cover property. Using "background-size:cover" property will give you the following advantages:
1. It Fills entire page with image, no white space
2. Scales image as needed
3. Retains image proportions (aspect ratio)
4. Image is centered on page
5. Does not cause scrollbars
6. As cross-browser compatible as possible
Here is the css (if you want it to apply to the entire page) :
html {
background: url(../images/MainMenuScreen.jpg) no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
Hope this helps
I want to manipulate the image on mouseover , that only width changes , but the height remains same. I see the image canvas doesn't fit the actual image, so I don't see his hand anymore. How can I just stretch the width?
http://jsfiddle.net/Z8knE/3/
div
{
background-image: url( http://t2.gstatic.com/images?q=tbn:ANd9GcQmloy1dlrNWhp8Y2u3lEKYEnLvJAqWVhggUIrA_QwRxjenmus-Ww);
-webkit-background-size: 100%;
-moz-background-size: 100%;
-o-background-size: 100%;
background-size: 100%;
height:150px;
width:150px;
}
Try something like this:
JSFIDDLE
You don't need to use jQuery, just use pure CSS.
Remove:
background-size:100% 150px;
...and add:
max-height:150px;
The trick is that background-size can have both width and height arguments passed. Set the width to 100% and the height to whatever static height you'd like. Then, when the box expands, the image will get wider and not taller.
http://jsfiddle.net/Z8knE/5/
div
{
background-image: url( http://t2.gstatic.com/images?q=tbn:ANd9GcQmloy1dlrNWhp8Y2u3lEKYEnLvJAqWVhggUIrA_QwRxjenmus-Ww);
background-size: 100% 150px;
height:150px;
width:150px;
}
Or, if you did not actually want the height on the box to change, like you have it in your original fiddle, you can simply remove that attribute from the jQuery like so:
Edit: This fiddle contains the below javascript http://jsfiddle.net/Z8knE/15/
$(document).ready(function(){
$("div").mouseenter(function(){
$("div").animate({width:"500px"},{duration: 1000, easing: 'easeOutBounce'});
});
$("div").mouseleave(function(){
$("div").animate({width:"150px"},{duration: 1000, easing: 'easeOutBounce'});
});
});