Sizing images with a blank source - html

I've got a long page, built with Angular. The images on the page are lazy-loaded so that the src is not set until the image is scrolled into view.
The container is flexible and the images should never scale larger than their dimensions (which I know and can set on a style attribute)
Right now I've having issues getting the images without a set source to scale properly.
TL;DR
I want <img src='pic.jpg'/> and <img src=''/>to take up the exact same amount of space inside a flexible container with maximum sizes.
DEMO: http://codepen.io/chrismbarr/pen/xGgGRq?editors=110
HTML (this will be generated from JavaScript where we know the dimentions ahead of time)
<div class="container" style='max-width: 500px; max-height: 700px;'>
Image with a source
<img src="http://lorempixel.com/500/700/cats/2/" />
</div>
<div class="container" style='max-width: 500px; max-height: 700px;'>
Image with no source
<img src="" />
</div>
CSS
img{
display:block;
max-width: 100%;
}
img[src=''],
img:not([src]){
//no image source
height: 100%;
width: 100%;
}
Here's a demo of the image sizes being hard-set so they are no longer flexible. This is what I want to avoid: http://codepen.io/chrismbarr/pen/JdEYMe

In the case that you know the dimensions of every image ahead of time, I almost always recommend the combination of a plain ol' <div> and the background-image property. You don't have to pander to the idiosyncrasies of the <img> tag, and you still get support for animated .gifs.
I whipped up this quick Codepen to give you a feel. I use a directive to set the width and height, which are passed into an isolate scope, then set the background-image property when I detect the directive top offset is less than the height of the window. Quick, dirty, but simple implementation of what I think you're going for.
Advantages:
Aforementioned reprieve from dealing with the ever cantankerous img tag.
Ability to add some neat hover effects (trying hovering over one of the cats in the Codepen).
Drawbacks:
Detecting image load with a background image isn't quite as easy as using the img.onload callback available for image tags. You could likely create directive template that used a img to squeeze out this functionality. Up to you.
Hope this helps!
EDIT: As Chris mentioned in a comment, this technique still doesn't address the aspect ratio issue when the image containers are of varying widths. To solve this I get to whip out one of my favorite CSS tricks, maintaining aspect ratio with padding-bottom, written about by Nicolas Gallagher.
While unfortunately I don't have time to add the fix into my original pen (headed to work), I did create this to show an implementation using the same images. The padding-bottom of an element will proportionally scale as the width of an element increases or decreases, thus maintaining the element's aspect ratio.

that's kinda simple what you do is
<img src="img.jpg" width"20px" height"20px"/>
or any number of pixels and do the same with he other one
<img src="" width"20px" height"20px"/>

Related

Core web vitals flagged Image elements do not have explicit width and height

I was checking Core Vitals on PageSpeed insight and noticed its flagging Image elements do not have explicit width and height and suggesting Set an explicit width and height on image elements to reduce layout shifts and improve CLS.
I am not sure what it exactly means and what i can do properly to resolve this issue, specific to my case
<img src="someimage.jpg" width="100%" height="100%" alt="something" class="img-responsive">
My page is responsive and i am using bootstrap v3.x for this webpage as its is old page. since page is responsive and i am using class="img-responsive" which automatically resizes image with, but this impacts core vital such as CLS.
Since layout is responsive what is the best approach to define use image to avoid CLS issue.
I have noticed most of the CLS reported by Page Speed Insigh is for owl Carousal
Below is the copy of code which generate CLS issue for images
<div class="container">
<div class="row">
<div class="col-md-12 col-lg-12 lc-hp-col">
<div class="owl-carousel owl-theme" data-items="1" data-items-desktop="1" data-items-tablet="[991,1]" data-items-mobile="[767,1]" data-pagination-speed="200" data-auto-play="true" data-stop-on-hover="true">
<div class="item">
<img alt="ALT" class="img-responsive" src="https://dummyimage.com/992x588/000/3431af&text=IMAGE+1">
</div>
<div class="item">
<img alt="ALT" class="img-responsive" src="https://dummyimage.com/992x588/000/3431af&text=IMAGE+2">
</div>
<div class="item">
<img alt="ALT" class="img-responsive" src="https://dummyimage.com/992x588/000/3431af&text=IMAGE+3">
</div>
<div class="item">
<img alt="ALT" class="img-responsive" src="https://dummyimage.com/992x588/000/3431af&text=IMAGE+4">
</div>
<div class="item">
<img alt="ALT" class="img-responsive" src="https://dummyimage.com/992x588/000/3431af&text=IMAGE+5">
</div>
</div>
</div>
</div>
</div>
CodePen link
Some article have suggested to use scrset for responsive images but this is not practical as we have to then upload multiple versions of same image.
<img
width="1000"
height="1000"
src="puppy-1000.jpg"
srcset="puppy-1000.jpg 1000w, puppy-2000.jpg 2000w, puppy-3000.jpg 3000w"
alt="Puppy with balloons"
/>
NOTE: The sizes of your images are fix as of Bootstrap mechanic!
If you have a nearer look to your page your images are responsive but not fluent. That means the size does change in predfined steps when the vieport changes the width. Inbetween this steps the sizes for the images are allways the same even if the sizes are set in percentage. That's the mechanic of Bootstrap.
So, - your are able to set fixed values to the sizes of your images without changing the layout!!!
You will find the original steps Bootstrap uses (if not changed for the project) here:
https://getbootstrap.com/docs/3.4/css/#grid-media-queries
As you see Bootstrap standard is: if viewport width becomes more than 769px the size changes, same as on 992px and on 1200px.
Taken from the codepen example the sizes of your images are:
// Up from Vieport width:
768px = Image: 720x426px
992px = Image: 940x557px
1200px = Image: 992x588px
(Note: below viewport widht 768pxcodepen does not work. Have a look for the size(s) on original page.)
Knowing that you are able to advice fixed sizes to the images by media queries. You may do this using sass with the original tools of Bootstrap (see link above). Or do something like this:
/* below 768px take values from original page */
#media (min-width: 768px {
.owl-carousel img {
width: 720px !important;
height: 426px !important;
}
#media (min-width: 992px {
.owl-carousel img {
width: 940px !important;
height: 552px !important;
}
#media (min-width: 1200px {
.owl-carousel img {
width: 992px !important;
height: 588px !important;
}
NOTE: I am not quite sure if that css overwrites the Bootstrap markup. So maybe you have to give it an higher specificity i.e. by using div.owl-carousel div imgor something similar. And if height is not correct please readout all sizes from original page. Sometimes you will need to be more exact i.e. with height: 588.xxxx px.
Answer
The width and height we are talking about, are intended to be a fixed number to avoid the warning.
That's needed to reserve the (explicit) required space for the image while it's loading. If you give it a percentage, the browser cannot know the size it will need, so it will be changing, and cause the page layout to shift (that's what we try to avoid).
Edit
I'm not sure about what you mean with "it becomes even harder". No one said it's easy, as you have a complex problem.
You are trying to:
Serve a responsive carousel.
A carousel with responsive images.
Avoid warnings from Web Vitals about Layout Shifts.
Complex solutions for complex problems, that's what it is.
There is no real solution to this issue other than the srcset solution that you mentioned. The layout shift issue will likely be flagged unless you specify image dimensions.
I agree that the integration of multiple image sizes is difficult & cumbersome & perhaps not always justified. Even if you integrate the multiple sizes of images you can still have a layout shift if the images are set to scale responsively to ANY size rather than just a set of options.
The CLS is less likely to be flagged by Google (or to bother any users) if your images begin to load very quickly so that the image sizes are known before the layout has a chance to fully render (& thus shift). Defer anything you can to bring the images towards the front of the line.
This may be questionable but I implemented a tiny generated png to get the image data loaded very quickly like this:
<img class="img_scale"
src="data:image/png;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs="
data-src="/img/img.jpg"
/>
You may also be able to use csscalc to estimate the percentage, pixel value or em value of a container for the image in order to greatly reduce the amount of shift. You probably can't eliminate it without using static sizes but you can cut it way down.
You can work around this problem by
Setting explicit <img width height> - for height value use your best guess what the most image heights will be
Later override the HTML element height attribute with the following CSS:
.my-img {
height: auto;
}
However note that this causes cumulative layout shift, CLS, event after the image is loaded, so you are essentially shifting the problem around. The CLS issue can be worked around by making sure the container element hosting the image has min-height set.
Here is the full source code for an example Svelte component where I worked around this problem.
When you use img src tag so you need to add width and height whatever actual image width and height attribute with img tag for an Example like this:
So it is not Create CLI in google page insights.

using CSS Responsive Image width and height with Google Structured Data recommendations

Google says that it is better to put the width and height of an img in the html: "A web browser can begin to render a page even before images are downloaded"
See Here
<img src="some-address.jpg" width="20px" height="20px">
But, what if the img is in a responsive page?
I did not give any value and the img works well and adapts to any size. But, then the Google testing tool for structured data gives an error: "A value for the width field is required"
https://search.google.com/structured-data/testing-tool
I tried to give that values:
<img src="http://www.w3.org/html/logo/downloads/HTML5_Badge.svg"
width="100%" height="auto">
Here is the example: JSFiddle
It is responsive and it has the values. The error goes away. But I have read that Google requires numeric values.
How to put the width and height of an img in a responsive page?
I suppose that the use of structured data is always recommended. So, I must take into account what the Google testing tool says. Am I right?
This is best done through a css style sheet as the width and height tags for images are generally considered bad practice.
.imageclass{
width: 100%;
max-width: 150px; /* whatever size is the biggest that you want */
height:auto;
}
<img src="http://www.w3.org/html/logo/downloads/HTML5_Badge.svg" class="imageclass" />
Just use css instead of attributes:
img {
width: 100%;
height: auto;
}
<img src="http://www.w3.org/html/logo/downloads/HTML5_Badge.svg">
The article you refer to says:
Specify a width and height for all images. A web browser can begin to render a page even before images are downloaded, provided that it knows the dimensions to wrap non-replaceable elements around. Specifying these dimensions can speed up page loading and improve the user experience. For more information about optimizing your images, see Optimizing Web Graphics on the site Let's Make the Web Faster.
So the reason of specifiing sizes in pixels is that browser will know the image size before it loads the image itself. And there is no sence in specifiing them in css for every image if it is unique and takes all place it needs. Now you are setting one value to auto. With auto browser have to get the image and only then it will be capable to calculate its dimensions ratio and use it. No any reasons to use attributes.
As Unor says here link to a another question
Schema.org’s height/width properties are not for stating in which dimension the image should be displayed, but which dimension the image file has.
So I can put the responsive css as ususal in the css file:
img {
width: 100%;
height: auto;
}
In the html, with structured data I have to give the width and height in px. The real pixels, as I can see in Photoshop:
<div itemprop="image" itemscope itemtype="https://schema.org/ImageObject">
<img src="some-address.jpg"/>
<meta itemprop="url" content="some-address.jpg">
<meta itemprop="width" content="20">
<meta itemprop="height" content="20">
</div>

How to Scale Down a Large Image Using HTML and/or CSS

What is the best way to get a smaller version of an image I want to use onto a webpage, but still allow the person to view the full image if they click "view image"? This question could really be broken down into two parts:
Say my image is 900x900px: Is there a way I can display that image at a much smaller size, like 100x100px (so that the browser does not have to load the entire 900px image) but allow the person to see full size image if they click "view image"?
Additionally, what is the best way to take the 900px image, and display it at only 100px? Assuming I can't do this ahead of time with photo editing software, should I use the height and width tags in HTML or in CSS? (It seems like they both resize the image (scale) rather than crop). Thanks
With the usual approach to use the heightand width attributes, the whole image still has to be transferred to the browser.
So if you add a link somewhere (the image itself could be the link), the user is still able to access the complete (900 x 900 px) image.
Regarding image cropping: There is some trickery you can use as outlined in this SO answer.
JsFiddle Demo 1 (the image itself is used as a link to the original full-sized image)
JsFiddle Demo 2 (using the first demo as a base, but this time cropped the image)
Easiest way is to use it as a background to a div and then use the background-sizeattribute. An example would be what I did with my website.
<div id="image"
style="background-image:url(images/Greensburg-Commons-Oblique2.jpg);
background-position:20% 20%;
background-size:600px 800px;">
</div>
Using this method, I was able to take a 3200x2400 photo and scale it down to 800x600 photo. Plus, In my opinion, it's a lot easier to style a div with a background photo than just a plain image and I feel it just does more. Just so you know, background-position changes what part of the scaled in photo you show :)
<div id="image"
style="background-image:url(images/Greensburg-Commons-Oblique2.jpg);
background-size:100% 100%;">
</div>
Also, you could change the background size to 100% by 100% and that way the background will display the full image all the time and will automatically scale down as your window size changes or screen size :). Best for fluid layouts.
well you can set the image as a background of a div and then set the background-size property
#yourDiv{
width:100 px;
height:100 px;
background:url('path/to/your/image');
background-size: 100px 100px;
}
you could set different properties for :hover but you'd need to use javascript to change the properties onclick
You can use a lightbox or with just CSS, but it will resize the page. Now this is a very simple example so don't expect a beautiful display.
HTML
<img src="img.png" class="resize">
CSS
.resize {
width:100px;
height:100px;
}
.resize:hover {
height:900px;
width:900px;
}
Now personally I would use a javascript or just a lightbox. It will look much better right out of the box with minimal adjustments. Just my 2 cents.

Pure CSS image thumbnails

I want to display a collection of image thumbnails in a grid. The images will come in a variety of sizes, but I'd like to restrict the thumbnails to a particular size (let's say 200px wide and 150px tall).
What I'd like to find are some magical HTML markup and CSS rules that will
Allow the images to be included in normal <img> elements
Ensure that the thumbnails fit into their 200x150 pixel box, retain their proportions, and are centered in whichever dimension they overflow.
Not require JavaScript or specific knowledge of each image's actual dimensions
I'm not sure if this is possible. I can make a (bad) approximation of what I want with the following markup:
<div class="thumb">
<img src="360x450.jpeg">
</div>
and CSS:
.thumb {
width: 200px;
height: 150px;
overflow: hidden;
}
.thumb img {
min-width: 200px;
min-height: 150px;
width: 200px;
}
This attempt breaks in a variety of ways:
Images that are in portrait orientation will be sized correctly, but will overflow through the bottom of the container, resulting in vertically-off-center cropping.
Images that are wide and short will be distorted in the horizontal dimension because of the hard-coded width and min-height rules.
But without that hard-coded width, images that are larger than the minimum height and width will not be resized at all.
If it's at all helpful, I've put up an example that will (hopefully) illustrate what I'm trying to do, here:
http://overloaded.org/tmp/imgtest/
http://overloaded.org/tmp/imgtest/imgtest.zip
I know that I can solve this problem by omitting the <img> element altogether and instead pulling the thumbnails in as a centered background image on the containing element, but, if it's possible, I'd like to keep the <img> elements in the page.
Thanks for any help or pointers you can provide!
Edit: I suppose I should note that an ideal solution will work in IE 6+ and modern browsers, but any solution that works in IE 9+ and other modern browsers (recent WebKit, Gecko, etc.) will be gladly accepted.
You can (kind of) achieve this with the CSS3 background-size additions: contain and cover.
Live Demo
contain (top picture) fits the entire image, keeping aspect ratio. Nothing is cropped.
cover (bottom picture) fills the containing element either vertically or horizontally (depending on the image) and crops the rest.
Possible, probably.
Also, probably not the best idea. Your big issue to overcome here is orientation of thumbnails. What if you're dealing with a panorama? Certainly, shrinking it down is going to create a very unsightly "squished" image, as would a very tall image. It's rare that everyone deals in 4X3 or 16X9 100% of the time. So, you'll need a mechanism to pad out the image. Even if the ratio is correct, it's not going to resize as cleanly as you could with a program like Photoshop or Gimp.
The other major issue in this thought process is that you're going to be sending massive amounts of unnecessary data to the server via the larger images. It'll take longer to load, fill up the DOM unnecessarily, and overall just inhibit the UI experience.
There are a number of ways to get around this, none of them pure CSS. I've tackled this several times, each in a unique way based on the client. For one client that wanted things totally custom, it was a custom uploader, resizing via iMagick (part of image magic) and custom CSS/Javascript for the album with major interactivity. In another instance, I use Gallery as the backend--handling the thumbnail creation, uploading, titling, cropping, and organizing-- and then just pulled the reformatted image links out of the DB to display them in a more appealing manner. You could save yourself even more trouble and just use something like the Flickr api to pull images for your use.
Here's a tut on using ImageMagick to do thumbnails.
.thumb img {
max-width: 200px;
max-height: 150px;
min-width: 200px;
min-height: 150px;
}
Well I know for thumbs you would want it max and min if you want a smaller image to make it bigger and bigger image to make it smaller.
try to set max-width and height and not min because if the image is not exactly that size it will overflow :)

Where to specify image dimensions for fastest rendering: in HTML or in CSS?

I've learned that it is a best practice to explicitly specify image dimensions. The browser can then already layout the page while still downloading the images themselves, thereby improving (percieved) page rendering time.
Is this true? And if so, is there a difference in specifying the dimensions in either HTML or CSS?
HTML: <img src="" width="200" height="100">
Inline CSS: <img src="" style="width: 200px; height: 100px">
External CSS: #myImage { width: 200px; height: 200px; }
According to Google Page Speed, it does not really matter if you specify the dimensions via CSS or HTML, as long as your CSS targets the IMG tag itself and not a parent element :
When the browser lays out the page, it needs to be able to flow around replaceable elements such as images. It can begin to render a page even before images are downloaded, provided that it knows the dimensions to wrap non-replaceable elements around. If no dimensions are specified in the containing document, or if the dimensions specified don't match those of the actual images, the browser will require a reflow and repaint once the images are downloaded. To prevent reflows, specify the width and height of all images, either in the HTML tag, or in CSS.
However, note that they advise not to resize the image using these dimensions, ie to always use the real dimensions :
Don't use width and height specifications to scale images on the fly. If an image file is actually 60 x 60 pixels, don't set the dimensions to 30 x 30 in the HTML or CSS. If the image needs to be smaller, scale it in an image editor and set its dimensions to match (see Optimize images for details.)
I tend to do it in the CSS. This is certainly a win when there are multiple images with the same dimensions (so you can do stuff like .comment img.usergroup { width: 16px; height: 16px; }), and have the same images subject to scaling in different stylesheets like user-selectable themes.
When you have completely independent images that are used on the site only once, it doesn't really make sense to abstract their size out to CSS, so the HTML version would probably be more appropriate there.
I think CSS gives you more flexibility: you can specifically set the width or height while setting the other dimension to auto. But when setting both dimensions, I don't thing there's a difference.
This does not answer your question directly, but I would not rely on the dimensions of your image for page layout. Instead include the image in a block level element. This relieves both the HTML and CSS from having to hold information that it really shouldn't as the image may change from time to time.
If you put a large image in an HTML page without dimensions, you should definitely notice the page layout shifting as the image is downloaded (over an internet connection, if not locally).
As per other answers, it doesn’t make much difference whether you do this in the HTML or the CSS.