The same img in two sizes in the html - html

I have an img for a large screen and another for small screens.This is an easy option and if works but I am not sure if there it is a good practice to put the same img in different sizes in the html and hide one with display none? is there any other problem with that option?
CSS:
#small {
display:none;
}
#media screen and (max-width: 630px) {
#big { display:none; }
#small { display:block; }
}
HTML:
<img id="big" src="img/1-big.jpg">
<img id="small" src="img/1-small.jpg">

IMUO I think this is not a good practice, because you are loading all the images twice (and hidden then). If you are using bootstrap (or responsive page) you could use the class img-responsive or this:
img {
width: 100%;
height: auto;
}
Or if not, you could do this:
/* For width smaller than 400px: */
body {
background-image: url('1-big.jpg');
}
/* For width 400px and larger: */
#media only screen and (min-width: 400px) {
body {
background-image: url('1-small.jpg');
}
}
Doing that way, you only load the image when needed and avoid load twice the images. Another example as background image: https://www.smashingmagazine.com/2013/07/simple-responsive-images-with-css-background-images/

I don't see anything wrong with this. In fact, it is a recognised technique to reduce page load times and to keep page sizes down on mobile (providing, of course, that you only load whichever image is required for your device size).
Also note, as the only potential pitfall I can see with this, is that that simply setting the CSS property to display: none does not always prevent an image from loading (see here: Does "display:none" prevent an image from loading?)
An alternative to this would be to have images stored with the same name and a small or no suffix (for larger images) added to them (almost like you have in your example), except only have 1 html element on the screen at any one time and modify the paths using javascript. Example;
// HTML ELEMENT
<img class='thumbnail' src='img/thumb.png'>
// JAVASCRIPT
if(window.innerWidth < 640){
// This is for users with smaller screens, load the smaller image
var imgs = document.getElementsByTagName('img');
for(var i = 0; i < imgs.length; i++){
var current = imgs[i].getAttribute('src');
imgs[i].setAttribute('src', current + '-small.png');
// THIS WOULDN'T WORK AS IS, AS IT WOULD PRODUCE '.png-small.png'
// AND IS INTENDED **ONLY** TO ILLUSTRATE A CONCEPT
}
}

Related

Can I use media queries based on box area?

I am trying to make a rectangular block of text responsive on different screen dimensions, occupying as much space as possible without overflowing. The text can be wrapped at arbitrary positions to new lines. As the screen can have different orientations, shapes (draggable window), and pixel densities, I am thinking perhaps I should vary the font size according to the area of the block displayed. Is this possible at all?
Something like this:
#media max-screen-area: 1600cm^2 { section { font-size: 1cm; }}
#media max-screen-area: 1000cm^2 { section { font-size: 0.8cm; }}
What is the best solution to my problem?
This kinda solved my problem:
function resize() {
for (let i = 0; i < 8; i++) {
document.querySelectorAll("section>div:first-child")[i].style.fontSize =
Math.sqrt(window.innerHeight*window.innerWidth/2000)+"px";
}
}
resize();
window.onresize = resize;

Is it possible to maximize the dimension of a specific image according to the size of a browser window using greasemonkey/tampermonkey?

For instance if I have a gallery of images that I can browse through, sometimes having multiple galleries open, I have to be careful in resizing one window because it will resize differently for another one of the same page.
The best example I can think of is when you open an image by itself in a new tab and it's auto resized proportionally in the middle of the page no matter big or small the window is. No scrolling required
If it helps here's an example of the code code where the image is shown
<div id="i3">
<a onclick="return load_image(2, 'f46ef2b433')" href="https://testsite.com/b/f46ef2b433/1341428-2">
<img id="img" src="http://testsite.com/fold01/5dde3b620790893d3ffab2da2437077dd41b31cf-230842-1280-1820-jpg/keystamp=1550591100-88d6d61f5f;fileindex=66272627;xres=2400/_000.jpg"
style="height: 1820px; width: 1280px; max-width: 1280px; max-height: 1820px;" onerror="this.onerror=null; nl('27617-430719')"></a></div>
the xpath is: //*[#id="img"]
I've seen plugins do this with videos but I'm looking to just do it with an image. Looking at other "similar" examples is confusing me more than helping at this point
(function() {
'use strict';
var x;
x = document.getElementById("img");
x.style.maxHeight = "100vh";
x.style.maxWidth = "100vw";
x.style.width = "";
x.style.height = "";
x.style.position = "fixed";
x.style.top = "0";
x.style.left = "15%";
})();
Here is my current updated script. i've been unable to change the max-height and max-with values but everything else has worked out for the most part. Without that, I'm not able to finish the task unless there's another method
x.setAttribute("style", "max-Height: 100vh");
this works but wiped away all of the other attributes...
both seem to work only in the console and not in the script as far as modifying the max height and max width values. there's no problem with changing other values
From what you described, you can use vh and vw units. Those units are relative to the size of the viewport.
Try the following exemple in a empty page. The display: body on the image avoid to have a vertical scrollbar
html,
body {
margin: 0;
padding: 0;
}
img {
display: block;
max-height: 100vh;
max-width: 100vw;
}
<a href="https://stackoverflow.com">
<img src="http://www.dummyimage.com/1000x4000/000/fff&text=1000x4000">
</a>

How to Load Different Home Page according to screen size

I want to load different home page according screen size. Can anyone help about it ?
For Example,
for screen-size < 960 px I want to display default landing page as index1.html
and
for screen-size > 960 px I want to display default landing page as index2.html
Thanks in advance.
I know this was asked and answered a while ago, but I think the solution I'm adding is better than the accepted answer as it involves no reloading and works on resizing. Define two CSS classes, .HideOnMobile and .ShowOnMobile and use them in two top level DIV elements.
Then use media queries to set the display value of those two classes to non or initial, to display or hide each DIV according to the screen width.
#media (max-width: 575.98px) {
.HideOnMobile {
display: none;
}
.ShowOnMobile {
display: initial;
}
}
#media (min-width: 576px) {
.HideOnMobile {
display: initial;
}
.ShowOnMobile {
display: none;
}
}
<div class="ShowOnMobile">
MOBILE content
</div>
<div class="HideOnMobile">
DESKTOP content
</div>
You've tagged this question responsive-design, but you are asking about how to do "adaptive design." Responsive design would be having a single HTML page that adjusts to the medium it is being viewed in, for example by using media queries. I won't get into a debate about which is better, but I add this in case you're interested in responsive design so that you have some ideas to google.
A way to do what you are asking is to have a bit of JavaScript on your page that checks the width of the window and redirects if necessary:
// In index2.html
if (window.innerWidth < 960) {
window.location = "index1.html";
}
// In index1.html
if (window.innerWidth >= 960) {
window.location = "index2.html";
}
I tried the above solution. It worked but the page was reloading continuously. By this approach solved the reload problem and I've added a function that can help reload the page automatically when viewport size change.
// refreshing page automatically when viewport size change
window.onresize = function(event) {
document.location.reload(true);
}
var href = window.location.href.split("/")
var html_location = href[href.length-1]
if (window.innerWidth >= 960 && html_location !== "index.html") {
window.location = "index.html";
}
if (window.innerWidth < 960 && html_location !== "index2.html") {
window.location = "index2.html";
}

Allowing images to shrink, but not stretch

I have a site with 4,000+ pages and 10 or more jpeg images per page, of varying sizes. I'm trying to make the site more mobile friendly. To that end, i want to make it possible for the images to shrink to fit on smaller screens. I know that i can do something like this to signal that the images can shrink:
img.bodyImg
{
width: 100%;
max-width: 357px;
height: auto;
}
But what if not all images have a width of 357 (or whatever), and i don't want smaller images stretched beyond their true dimensions? And just to make things more fun, what if the images tags don't have height and width attributes specified?
My goal is to find a solution that doesn't require me to adjust tens of thousands of image calls manually, but i can do a search and replace. Images are currently wrapped in a div container and have a class, like so:
<div class="imgDiv"><img class="bodyImg" src="http://www.example.com/image.jpg"></div>
I'm also open to the possibility that i'm going about this in the wrong way entirely.
Using max-width is simple, effective, and requires no JavaScript.
The CSS below creates responsive images that shrink to fit the container's width but won't expand beyond their native sizes.
img.bodyImg {
max-width:100%
}
In the demonstration below, both images are 300px X 75px. The first container is 200px wide and the second one is 400px wide. Notice that the first image shrinks to fit in the container, but the second image does not expand beyond its native size. Also note that the proportions of each image remain accurate.
div {
background-color: #CCC;
margin:0 0 .5em;
padding:.25em;
}
div.one {
width: 200px;
}
div.two {
width: 400px;
}
img {
display:block;
max-width: 100%;
}
<div class="one">
<img src="http://lorempixel.com/300/75/abstract/4/" />
</div>
<div class="two">
<img src="http://lorempixel.com/300/75/abstract/4/" />
</div>
Additional Notes
I've included display:block to remove the descender space below the image.
If your images have specific height and width attributes (as they arguably should), you can add height:auto and/or width:auto to override those attributes.
Bootstrap uses this method for responsive images.
You can use a little jQuery to figure out each image's native width, and set perscriptive max-widths for each image afterward:
$('.bodyImg').each(function() {
// Create new offscreen image to test
var theImage = new Image();
theImage.src = $(this).attr("src");
// Get accurate measurements from that.
var imageWidth = theImage.width;
$(this).css({
"max-width" : imageWidth
});
}
UPDATE: And if you want each image to have a uniform width, you can store the smallest max width and apply it to all of the images:
var smallMax;
$('.bodyImg').each(function() {
// Create new offscreen image to test
var theImage = new Image();
theImage.src = $(this).attr("src");
// Get accurate measurements from that.
var imageWidth = theImage.width;
// if the variable exists and is bigger than
// the current width, use the new max width
if (smallMax !== undefined && smallMax > imageWidth) {
smallMax = imageWidth;
}
// set the variable if it hasn't been set yet
else if (smallMax == undefined) {
smallMax = imageWidth;
}
// keep the old variable if it is defined and smaller
else {}
$(this).css({
"max-width" : smallMax
});
}
Why not just:
max-width:100%; /*Ensure the width scales to the width of the parent container*/
width:auto; /* Not required, but sometimes is nice to ensure the width not being overridden by other factors like browser quirks */
height: auto; /*Ensure the image keeps its ratio*/
Try using max-width:100% and height: auto in your css. If you want to make your site mobile friendly I would suggest looking into bootstrap framework for more flexibility.

Mobile iOS - Fixed background image solution

I know similar issues have been asked several times before but I have trawled through many questions/ answers and cannot find a solution that works for my specific issue.
Basically I have a responsive website which has fixed background images - the images are 1280 x 853 px, they are applied to the html tag via the following css (which is currently a bit of a mess due to trying several solutions) -
html {
background: url(/content/images/bg_lrg.jpg) no-repeat top center fixed;
-webkit-background-size: 1024px 768px;
background-attachment: fixed;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
My idea was to apply a background size - if this worked I'd use media queries to apply relevant sizes for ipad / iphone / other.
the image currently appears huge in iOS devices - as it is constraining itself to the height of the document rather than the viewport - I know there are many issues with fixed backgrounds in mobile Ios - does anyone have a workaround solution? where my image could cosntain to viewport width not document height?
First Solution, have you tried setting your ViewPort? In the head of your HTML, you can include this:
<meta name="viewport" content="width=device-width, initial-scale=1">
I would first try that. You can even specify the width for iPhones. This is the best solution at first in order to get your device to display the size of the image properly on your phone. Here is a link with a quick description of what you can do with ViewPorts:
Many sites set their viewport to "width=320, initial-scale=1" to fit precisely onto the iPhone display in portrait mode. Using the viewport meta tag to control layout on mobile browsers
Secondary Solution:
If that doesn't work, I created a modified this custom solution before these new feature came out. I modified this function to make the background of a website always fill the background regardless of screen size:
JavaScript using JQuery:
//Resize background image function
$(function () {
var $window = $(window);
var width = $window.width();
var height = $window.height();
setInterval(function () {
//Checks for screen resize every hundreth of a second and resizes elements based on that new screen size
if ((width != $window.width()) || (height != $window.height())) {
//resets the variables to prevent glitching
width = $window.width();
height = $window.height();
//calls resizing functions
resizeBg();
}
}, 100);
});
And it calls this function:
function resizeBg() {
var theWindow = $(window),
$bg = $("#bgVideo"),
aspectRatio = 1920 / 1080; //-- This is the aspect ratio (width / height) of the background image. if the video changes size.
//actually apply aspect ratio
if ((theWindow.width() / theWindow.height()) < aspectRatio) {
$bg.removeClass().addClass('bgheight');
} else {
$bg.removeClass().addClass('bgwidth');
}
}
In my CSS I have the following classes:
.bgwidth {
width: 100%;
}
.bgheight {
height: 100%;
}
And on your HTML, you want to have something like this:
<video id="bgVideo".....
OR
<img id="bgVideo"...
and I have the following CSS for my background ID:
#bgVideo {
position: fixed;
top: 0;
left: 0;
z-index: 1;
}
I hope this helps.