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");
}
}
Related
Hello everyone~ I have a problem but my English is not good. I will try my best to express it completely! If the explanation is not clear enough, everyone is welcome to tell me~ The
problem is like this, today there is a block for users to upload photos !
The width and height of this photo after uploading by the user
cannot exceed 360px, the minimum cannot be less than 100px, the
maximum height cannot exceed 200px, and the minimum cannot be less than 100px
.
What I want to ask everyone here is, can this requirement be accomplished only by CSS?
Or can it be accomplished by using JavaScript? But if I use JavaScript, I don't know how to start, because my JavaScript is very poor. I hope I can get your valuable suggestions here, thank you.
I wrote an example. The original picture size is only 50PX in height. How can the height of the photo reach 100PX without affecting the ratio?
.photo{
width: 360px;
height: 200px;
object-fit:contain;
object-position:left center
}
<div class="demo">
<img class="photo" src="https://upload.cc/i1/2021/09/30/s73jb5.jpg" alt="">
</div>
I think this is what you want to do.
Image should have maximum-width to be 360px and minimum height should be 100px.
And also if you want to add min-width and max-height you can add in imageSettings variable in javascript.
If you have multiple images, simply add imageContainerForJS class to img parent element.
(()=>{
let imgContainers = Array.from(document.querySelectorAll('.imageContainerForJS'));
const imageSettings = {
"max-width": 360,
"min-height": 100,
}
for(let imgContainer of imgContainers) {
let img = imgContainer.querySelector('img');
if(!img) continue;
let imageSource = img.src;
let image = new Image();
let maxWidth = imageSettings['max-width'] || null;
let minWidth = imageSettings['min-width'] || 0;
let maxHeight = imageSettings['max-height'] || null;
let minHeight = imageSettings['min-height'] || 0;
image.onload = function() {
let width = this.width;
let height = this.height;
if(maxWidth && width > maxWidth) width = maxWidth;
if(minWidth && width < minWidth) width = minWidth;
if(minHeight && height < minHeight) height = minHeight;
if(maxHeight && height > maxHeight) height = maxHeight;
imgContainer.style.width = width+'px';
imgContainer.style.height = height+'px';
}
image.src = imageSource;
}
})();
.photo{
object-fit: cover;
object-position: center;
width: 100%;
height: 100%;
}
<div class="demo imageContainerForJS">
<img class="photo" src="https://upload.cc/i1/2021/09/30/s73jb5.jpg" alt="">
</div>
You can use object-fit:cover to make your image proportionally expand to fill its container.
Set the container to the dimensions you want, then have the image fill it by setting its width and height be 100%.
By default cover will position the image in the centre.
.demo {
width: 360px;
height: 200px;
}
.demo .photo {
width: 100%;
height: 100%;
object-fit: cover;
/*object-position: left center;*/
}
<div class="demo">
<img class="photo" src="https://upload.cc/i1/2021/09/30/s73jb5.jpg" alt="">
</div>
I have images of size 700px(width) x 333px(height) which have aspect ratio 2.10. I Want to display these images in a grid.The size of each element in the grid is 327px(width)and 183px(height) aspect ratio 1.77.The original images could be cropped or resized with minimum distortion and final aspect ratio of each element should be 1.77 and displayed as 327px(width)and 183px(height).clip doesn't work as it "clip"s all other images in the view.Also, there is another background image (like a logo) over which the new images are dynamically rendered.So background-image:url(img-url); won't work
How to achieve this through CSS?
Simply use it as a background image and resize it as you need :
div {
width:327px;
height:183px;
background-image:url(https://lorempixel.com/700/333/);
background-size:cover;
}
<div></div>
The aspect is ratio is not quite right 183*1.777=325.191
333/183 = 0.5495 // scale factor - so cropping width
700*.549= 384
384-325=59
crop left and right 30px approx
css
div.myimage{
width: 325px;
height:183px;
}
div.myimage img{
width: 385px;
height: 183px;
marginLeft: -30px
marginRight: -30px;
}
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.
In bootstrap I have a fixed top nav bar and fixed bottom nav bar. I want to show a large image in the background between the space of those two nav bars and I also want to cover the width of the window. How can I dynamically get the height between the navbars and the width of the window? The window size may change depending on device.So I need it dynamic
Requires jquery:
var viewport = {
width : $(window).width(),
height : $(window).height()
};
//can access dimensions like this:
//viewport.height
Though you won't always get perfect results, different devices behave differently and this gives the viewport dimensions, not the screen dimensions.
Alternatively you could check the width of a data-role="page" element to find the device-width (since it's set to 100% of the device-width):
var deviceWidth = 0;
$(window).bind('resize', function () {
deviceWidth = $('[data-role="page"]').first().width();
}).trigger('resize');
$(window).resize(function() {
var top_nav_height = $("#id_of_top_nav").height();
var bottom_nav_height = $("#id_of_bottom_nav").height();
var window_height = $(window).height();
var height_of_open_space = window_height - (top_nav_height+bottom_nav_height);
$("#id_of_img").css({
height:height_of_open_space+'px';
});
});
this will be fine with if 0px padding and margin, if not also get that values and subtract from height_of_open_space before applying to img height
It is a bit hard to tell without seeing any of your markup, but it should be feasable with pure css. I set up a very basic example to demonstrate:
http://codepen.io/anon/pen/XbGJJO
HTML:
<div class='top'>
top navbar
</div>
<div class='content'>
<p> some content </p>
</div>
<div class='bottom'>
bottom navbar
</div>
CSS:
.top, .bottom {
height: 40px;
background: red;
position: fixed;
width: 100%;
}
.top {
top: 0;
}
.bottom {
bottom: 0;
}
.content {
margin: 40px 0;
min-height: calc(100vh - 80px);
background: green; /* background goes here */
}
The trick lies in the following line:
min-height: calc(100vh - 80px);
This tells your content to at least take up 100% of the vertical height, minus the height of the top and bottom bar. Let me know if you want me to explain further.
I am attempting to create a circle with a height of 10% the browser window. If I also make the width 10%, and you scale the browser, you get a misshapen or squished circle. I want to try to create the width of the circle with jquery to change in proportion with the height. so if 10% converts to 200px height, the width would be changed to 200px. I have tried a few solutions, but keep getting a width of 0px in return.
assuming you are using jQuery and your circle is an HTML element you could do this:
var $window = $(window),
$el = $('#someElement');
$window.on('resize', function () {
var size = $window.height() * 0.1;
$el.width(size).height(size);
});
Get the width and the height of the window and then simply check which one of them is the smallest. Get 10% of that value and use this as the circle's radius.
Little experiment using a transparent square image which is the direct child of <body>:
http://jsfiddle.net/2S3xU/3/
<html><body><img src="transparent-square.gif">
img {
border-radius: 99999px;
position: absolute;
top: 0; left: 0;
height: 100%; /* width will follow height to keep image undistorted*/
max-width: 100%;
max-height: 10%;
}
/* Opera fix*/
body, html {
width: 100%;
height: 100%;
}