• Home New Posts Forum List Trending New Threads New Media Spy
  • WikiPost Latest summaries Watched WikiPosts
  • Support FAQ and Rules Contact Us

Safari not computing image aspect ratios from width and height attributes

  • Thread starter sulliops
  • Start date Mar 30, 2021
  • Tags ios ios 14 macos macos 11 safari safari 14 webkit
  • Sort by reaction score
  • Web Design and Development

sulliops

macrumors newbie

  • Mar 30, 2021

I've recently implemented a lazy image loading feature on an image-heavy website, and have been having issues with reflow. I fixed the problem by manually specifying the image dimensions using the `width` and `height` image attributes, as below: Code: <img class="lazyload img-fluid" data-src"/path/to/image.jpg" width="200" height="400" /> It works great in every browser except Safari, but I'm confused because Safari 14 supposedly supports computing aspect ratios based on the `width` and `height` attributes . None of my up-to-date macOS or iOS devices seem to recognize this feature in Safari, but they do in every other modern browser. The expected outcome is that the spot on the page where the `<img />` tag is located should be reserved (painted) based on the calculated aspect-ratio using the `width` and `height` attributes, to be later replaced by the `data-src` attribute via the lazy-loading plugin. In Firefox and Chrome (+ Chromium-based browsers), the space is reserved until the image is loaded (to prevent reflow); in Safari, the space is not reserved and the page shifts after the image is loaded. Here's a CodePen example with near identical code to mine (you should open in Safari and click immediately on "Nav 4" to see the issue): https://codepen.io/sulliops/full/QWdwRxx Here's a screencap of my issue: https://gyazo.com/da76046282965f7a32ed3d85cc7423df Anyone have any clue as to what I'm doing wrong? I'm not worried about backwards compatibility (Safari doesn't support the feature in question before 14.0) or IE support, so this solution is perfectly fine for me until `aspect-ratio` becomes available in browsers other than Chrome. Safari is important, though, so I'll take any suggestions.  

arn

macrumors god

Hmm... the images on the front page are lazy loaded, and is working properly in saving the space. Let me look at your code a bit more closely.  

arn said: Hmm... the images on the front page are lazy loaded, and is working properly in saving the space. Click to expand...

I figured it out I think. You need a non empty "src" for Safari to calculate the size. try adding src=" https://images.macrumors.com/images-new/1x1.trans.gif " to your <img> html arn  

arn said: I figured it out I think. You need a non empty "src" for Safari to calculate the size. try adding src=" https://images.macrumors.com/images-new/1x1.trans.gif " to your <img> html arn Click to expand...
sulliops said: Wow, that is beyond inefficient — but it worked in the CodePen. Actually applying that fix on my production website didn't do much good, though — it actually broke compatibility with other browsers, including Safari, and the reflow issue is back in full swing. Any ideas? Click to expand...
  • Barry Pollard
  • Updated Jan 11, 2022

Setting Height And Width On Images Is Important Again

  • 17 min read
  • Browsers , Performance , Optimization , Core Web Vitals
  • Share on Twitter ,  LinkedIn

About The Author

Barry Pollard is a web developer who is obsessed with web performance. He is the author of the Manning book “ HTTP/2 In Action ” and is a one of the maintainers … More about Barry ↬

Email Newsletter

Weekly tips on front-end & UX . Trusted by 200,000+ folks.

Web performance advocates have often advised to add dimensions to your images for best performance to allow the page to be laid out with the appropriate space for the image, before the image itself has been downloaded. This avoids a layout shift as the image is downloaded — something Chrome has recently started measuring in the new Cumulative Layout Shift metric .

Well, a dirty, little, secret — not that well-known outside the hard-core web performance advocates — is that, until recently, this actually didn’t make a difference in a lot of cases, as we’ll see below. However, adding width and height attributes to your <img> markup have become useful again after some recent changes in the CSS world, and the quick adoption of these changes by the most popular web browsers.

Recommended Reading

The CSS contain property gives you a way to explain your layout to the browser, so performance optimizations can be made. However, it does come with some side effects in terms of your layout. Read a related article →

Why Adding Width And Height Were Good Advice

Take for example this simple page:

This might render in two stages, first as the HTML is downloaded, and then second once the image is downloaded. With the above code, this would cause the main content to jump down after the image is downloaded and the space needed to display it can be calculated:

Layout shifts are very disrupting to the user, especially if you have already started reading the article and suddenly you are thrown off by a jolt of movement, and you have to find your place again. This also puts extra work on the browser to recalculate the page layout as each image arrives across the internet. On a complex page with a lot of images this can place a considerable load on the device at a time when it’s probably got a lot of better things to deal with!

The traditional way to avoid this was to provide width and height attributes in the <img> markup so even when the browser has just the HTML, it is still able to allocate the appropriate amount of space. So, if we change above example to the following:

Then the render happens like below, where the appropriate amount of space is set aside for the image when it arrives, and there is no jarring shift of the text as the image is downloaded:

Even ignoring the annoying impact to the user in content jumping around (which you shouldn’t!), the impact on the CPU can also be quite substantial. The below screenshot shows the performance calculations performed by Chrome on a site I work on which has a gallery of about 100 images. The left-hand side shows the calculations when width and height are provided, and on the right when they are not.

As you can see, the impact is considerable — especially on lower-end devices and slow network speed, where images are coming in separately. This increases load time by a noticeable amount.

How CSS Interacts With Element Widths And Heights

Widths and heights on an image can cause issues when you try to alter them using CSS. For example, if you want to limit your images to a certain width you might use the following CSS:

This will override the width of the image and constrain it when necessary, but if you have explicitly set the height on the image tag, then we are not overriding that (only the width) and you will end up with a stretched or squashed image, as we have no longer maintained the aspect ratio of the image:

This is actually very easily fixed by adding a height: auto line to the CSS so the height attribute from the HTML is overridden too:

However, I find it still catches people by surprise and sometimes leads to them not specifying image dimensions in the HTML instead. With no image dimensions, you can get away with just specifying max-width: 200px in the CSS without having to specify height: auto and the browser will automatically figure out the height itself — once it has the image.

So, once we add the dimensions and that the height: auto trick, we get the best of both worlds, right? No layout shifts, but also the ability to resize images using CSS? Well until very recently you might have been surprised to find out the answer was in fact: no ( I was — hence why I decided to write this article).

For example, take the code below:

This would have resulted in this load:

Wait, what’s going on here? We’re back to the first problem. I thought I said that by specifying the image dimensions in the HTML you could avoid this layout shift problem? Well, this is where it gets interesting and will lead on to the main point of this article.

The problem is that, unless you were giving explicit width and height CSS values to your images — and who wants to limit themselves like that in a responsive world where you want the image to expand or shrink to fill up the available space — then CSS will need the dimensions from the image file itself to figure out the auto part of the dimensions. It ignored any width and height attributes set in the HTML.

The implication of all this is that specifying width and height attributes on images often wasn’t actually that useful in a lot of cases. Yes, when an image is being shown at full size, without any CSS changing any dimensions, it is useful to resolve the layout shifting problem. However, when you use CSS like below to ensure images do not overflow their available space, then you run into problems as soon as the available width becomes smaller than the actual image size.

This affects any page where we constrain the image size in a responsive manner — i.e. small screen mobile devices. These are likely to be the very users suffering with network constraints and limited processing power that will suffer most from layout shifts! Of course, we ideally should be delivering appropriately sized images for the screen size, but you cannot cover every device size, so often images will need some resizing by the browser, particularly on mobile.

Many websites may not bother to specify width s and height s on their <img> tags. That could be because they weren’t aware this was useful, or because they were all too aware of what we talked about here and knew it actually wasn’t that useful in a lot of cases. Whatever the reason is beside the point, they are frequently not provided. (How can we even evangelize putting the effort into using them given what I’ve just described?) Even the popular Lighthouse auditing tool doesn’t flag when you don’t do this (though in light of some of the things we’re about to talk about, that is under discussion again ).

Working Around The Problem

The limitations for responsive images have been known for a long time and many workarounds, including the so-called padding-bottom hack , have been created to work around the issue. This uses the fact that padding percentages (including padding-bottom ) are always based on the container width (to ensure a consistent padding even if height and width differ). This fact can therefore be used to create a container with where the height is set based on a ratio of the width. For example for, let’s say we have an image with an aspect-ratio of 16:9, then the following CSS code will create the appropriately sized space for the image:

The three main downsides of this technique are the following:

  • It requires a hard-coded ratio to be calculated ( 56.25% — 9÷16 — in this example), so it potentially requires custom CSS for each different image.
  • The CSS code is not exactly easy to remember — forgetting or removing a single line of the above CSS code will break the whole thing. Not to mention this technique requires all images to be wrapped in an extra container element.
  • This is a more advanced technique that not all web developers know about or use.

And, let’s be honest — it’s a bit of a hack! So, we really should fix this properly, shouldn’t we?

Fixing The Resizing Problem

The issue has been tackled from a few different directions by a number of different standards organizations.

The CSS Working Group (CSS WG) proposed the aspect-ratio property that Rachel wrote about previously . This would tackle the complexity problem (issue 2) once it becomes available, and simplify the above code to just this:

Much nicer! This is particularly useful for video where we usually have a set number of commonly used aspect-ratios, so we could create a few classes like above for each size. It’s perhaps less useful for images where dimensions are much less standardized, as it doesn’t solve issue 1 (custom CSS code required per image), nor issue 3 (website developers will need to remember to set this). So, it’s a step forward, but not a full solution.

Separate to this, the Web Incubator Community Group (WICG) — a group of browser developers and other interested parties that can experiment on technologies to see if they work before formal standardisation — also created a proposal to fix this . They proposed the intrinsicsize attribute, that would look like this:

As this is an HTML attribute, it can be set per image (solving issue 1), and is relatively easy to code (solving issue 2), but was still likely to suffer from adoption issues (issue 3) unless it became very well-known with a big push from the whole community.

We already have a common, well-known method of setting the width and height on <img> elements (even if they are not used as much as they should be!) so anything new, other than that, is going to suffer from the adoption issue. And that is where the (now seemingly obvious!) answer presented itself.

Jen Simmons proposed this elegant, and simple solution , that she had come up with, along with fantasai :

Rather than hard-coding the aspect-ratio , this uses the attr CSS function to create the appropriate aspect-ratio based on the image width and height attributes provided by the HTML. The attr function has been around for a while, but has been very limited in scope — it’s supported for content by all browsers , but not for the wider use case of any other attribute like width and height , which is what is needed here.

If attr was able to be used for the well-known width and height attributes from img elements, then it could use be used to automatically calculate the aspect-ratio as per above. This would solve issue 1 (no hard-coded aspect ratio needs to be set in the HTML nor the CSS), issue 2 (very simple to add) and, as we shall see, there is a very simple answer to issue 3 (adoption).

Basically, this solution means if the following four conditions are true, then the correct image dimensions could be calculated without needing to wait for the images to download, and so without the need of a content layout shift:

  • height is set on the element in HTML
  • width is set on the element in HTML
  • height (or width ) is set in the CSS — including using percentage values like max-width: 100%;
  • width (or height ) is set to auto in the CSS.

If any one of these were not set, then the calculation would not be possible, and so would fail and be ignored and have to wait for the image to be downloaded.

So once browsers support using the HTML width and height to calculate the aspect-ratio we can solve our problem very simply with no change in practice to HTML and one line of CSS code! As mentioned above, this is also something many web developers may have already assumed was happening anyway.

Driving Adoption Of This Solution

Because this is just a CSS attribute, the proposal contained a further twist — it could be added to the user-agent stylesheet used by browsers so would not even require any changes from web developers to benefit from this.

The user-agent stylesheet is where default CSS definitions are set (e.g. what font-size the h1 element uses), which can be overridden by your own CSS if you want. By adding the above aspect-ratio one-liner to this we don’t need to drive adoption — we basically turn it on automatically for all sites that meet the above four conditions!

However, this does depend on the attr function having access to the width and height HTML attributes, and also the upcoming aspect-ratio CSS property to be completed — neither of which has happened yet. So instead, as an easier fix, the browsers could implement the equivalent logic deep in rendering code rather than exposing it via the user-agent stylesheet, but the effect is the same. This alternative implementation approach was even suggested as part of the proposal .

Firefox went ahead and did this as an experiment and then turned it on by default for Firefox 71 . Once that was released, then your site may well have just got faster for free — thanks Mozilla! Maybe in future, they will move this to the user-agent stylesheet method, but for now, this is sufficient (and perhaps more performant?).

Backwards Compatibility

When introducing a change in behavior, there is always a concern about backwards compatibility and this feature was no different. In theory, as long as the four attributes were appropriately set, there should be no breakage with this.

However, when Firefox initially experimented with it, they discovered problems for those setting the width and height incorrectly in their HTML. Whereas previously these incorrect values would be ignored if the CSS overrode them, now they were being used when auto was set and the images were not displayed correctly and led to squished or stretched images. Now you could argue that web developers shouldn’t set these values incorrectly, and in some cases, it would be already broken even without this change (the case above when you didn’t set height: auto ), but still, breaking sites is never a good thing. That is also something the web tries very hard to avoid — and is mostly very good at avoiding that (it’s one of my favorite things about the web as a platform).

The solution to that problem, however, was relatively simple: have the actual image aspect-ratio of the image override any CSS calculated aspect-ratio. This way the (incorrectly) calculated aspect-ratio can be used for initial layout, but then can be recalculated when the image is downloaded, so the image is displayed as it was before. This does cause a layout shift (since the incorrect space was allocated initially) but that was happening before anyway, so it’s no worse. In fact, it’s often a lot better as an incorrect aspect ratio will often be closer to the truth than a zero aspect-ratio.

Rollout To Other Browsers

After Firefox’s successful experimentation, Chrome also decided to implement this (again using the layout coded method for now rather than default user-agent stylesheet), and rolled it out by default in Chrome 79 . This also took care of the other chromium-based browsers (Edge, Opera and Brave, for example). More recently, in January 2020, Apple added it to their Tech Preview edition of Safari , meaning it should hopefully be coming to the production version of Safari soon, and with that, the last of the major browsers will have implemented this and the web will become better and less jolty for a huge number of sites.

Limitations

There are a few limitations to be aware of with this feature, including issues with:

Art Direction

Lazy loading.

The fix works great to calculate the aspect-ratio based on a fixed width and height , but what about when those change? This is known as art direction and an example is shown below:

In this case we are using a wide image for desktop, and then a square, cropped image for mobile. Responsive images can be implemented with the picture element like this:

Currently, this only allows the width and height to be set once on the main, fallback <img> element and not on the individual <srcset> alternatives. Adding these has been proposed but until then, this is currently a limitation of the solution, and using images with different dimensions will still experience a layout shift.

Update (July 2021) : This was added in Chrome 90 .

This feature would be perfectly suited for use with lazy-loading. Ideally, all lazy-loaded images are loaded off-screen as you scroll down the page before the lazy-loaded image enters the viewport, but often this is not the case depending on how fast the user scrolls and the network, so having the image area correctly set would at least avoid the layout shift after loading does occur. Additionally, even when loading is happening off-screen, layout shifts can be costly in terms of CPU time, as we have shown above.

However, lazy loading techniques may involve not using an <img> element, or at least one without a src (to prevent the browser from downloading the image by default). Therefore, it may not be able to benefit from this recent change depending on how your browser handles the element used or src -less <img> elements. Though if the CSS version of this solution becomes available, then website developers will have greater control over specifying aspect-ratio themselves.

Native lazy loading was recently released by the Chrome team and it has since been added to the HTML spec . Other browsers are also looking to support this with Firefox also getting this soon , and Safari hopefully not too much later . That does make use of the <img> element with a src with syntax like the following (including when used as part of the <picture> element):

Perfect! Well, unfortunately, I discovered this height and width solution is not compatible with the recently released native lazy-loading functionality as can be seen on this test page . I’ve raised a bug for this issue and hopefully the Chrome team will fix this soon. ( Update: This was fixed in Chrome 83. )

Currently, the browsers that have implemented this, have only done for the <img> element, but it would also be useful for <video> , <iframe> and <object> elements to name a few, and this under discussion . Again, if the CSS version of this technique becomes available through the attr functions and aspect-ratio property, then that puts the power in the website developer to implement this for whatever elements they want!

Update (Oct. 2021) : CSS aspect-ratio support was since added in Chrome 88, FireFox 89 and Safari 15 but not yet with the ability to set these via data attribute references.

I love improvements that just work without any effort required of website owners. That is not to ignore the hard work required by the browser developers and standardization teams, of course, but it’s often rolling out to websites that is the real difficulty. The less friction we can add to introduce these improvements, the more likely they will be adopted, and there’s no better friction than none at all! Fixing the impact of layout shifts on users for responsive images seems to be one such improvement and the web is all the better for it.

The one change that is required of us web developers is to ensure we are providing width and height attributes in our markup. It’s a habit we shouldn’t really have gotten out of, and many CMS and publishing tools make this relatively easy. I queried the HTTPArchive and it looks like 62% of <img> tags have width or heights , which is way higher than I expected to be honest — but let’s try to increase that statistic even more now we have a reason to again. So, I implore you to check that you are doing this on your sites and, if not, start to. It will improve the experience for your users and ultimately make them happier, and who doesn’t want that?

Smashing Newsletter

Tips on front-end & UX, delivered weekly in your inbox. Just the things you can actually use.

Front-End & UX Workshops, Online

With practical takeaways, live sessions, video recordings and a friendly Q&A.

TypeScript in 50 Lessons

Everything TypeScript, with code walkthroughs and examples. And other printed books.

Safari not computing image aspect ratios from width and height attributes

  • Safari and Web

safari image width auto not working

Avoiding <img> layout shifts: aspect-ratio vs width & height attributes

By default, an <img> takes up zero space until the browser loads enough of the image to know its dimensions:

When you run the demo, you'll see the <figcaption> immediately. Then, after a few seconds, this paragraph and subsequent page content shifts downwards to make room for the image. This makes the user experience massively frustrating, as content moves out from under the user's eyes/finger/pointer.

For over a decade, we had to use silly hacks to manually apply an aspect ratio, and then, bloody typical, two better solutions arrived at roughly the same time. They are CSS aspect-ratio , and width & height presentational hints.

So, which should you use? First, let's take a look at how the features work, as there's quite a bit of misinformation out there…

CSS aspect-ratio

If you do this:

…you get this:

This feature became cross-browser compatible once it landed in Safari 15, late 2021, having arrived in Chrome & Firefox earlier that year.

It works on any element, but here's a demo with <img> :

This time, the image reserves space for its content as soon as it appears in the document, so stuff doesn't shift around once it loads.

The other solution is…

Width & height presentational hints

If you set dimensions on your image:

And set height to auto :

…the image will have an aspect ratio applied, even before it loads.

This landed in Chrome and Firefox back in 2019, and became cross-browser compatible when it landed in Safari 14 a year later. So, this feature has been around a little longer than CSS aspect-ratio .

In addition to <img> , this feature also works on <video> and <input type="image"> .

Update: Although browsers implemented the feature for <video> as per the spec, the spec is broken , so it doesn't work in practice.

However, there's a bit of misinformation floating around…

No, this doesn't use attr()

A lot of articles say this feature works via a user-agent stylesheet like this:

This isn't how it actually works

Firstly, this feature doesn't work on embed , iframe , marquee , object , or table . But also, this usage of attr() wouldn't work in practice because it returns a string. To make it work properly, you'd need to cast the attribute to a number, which CSS supports!

This isn't how it works either

But this isn't how it works, because:

No browser supports attr on all properties

…no browser supports attr() , aside from very particular cases like content on pseudo-elements. Hopefully that will change one day!

How does it actually work?

Here's what the spec has to say:

The width and height attributes map to the aspect-ratio property (using dimension rules) on img and video elements, and input elements with a type attribute in the Image Button state. — Attributes for embedded content and images - HTML

So, it does map to the aspect-ratio property. Specifically:

…the user agent is expected to use the parsed dimensions as a presentational hint for the 'aspect-ratio' property of the form auto w / h . — Mapping to aspect-ratio - HTML

You can think of a "presentational hint" as something a bit like a zero-specificity inline-style that's applied internally.

This uses a feature of aspect-ratio I didn't mention earlier:

The new bit is auto . Here's what the spec says:

If both auto and a <ratio> are specified together, the preferred aspect ratio is the specified ratio of width / height unless it is a replaced element with a natural aspect ratio , in which case that aspect ratio is used instead. — CSS-sizing level 4

A lot of articles gloss over this, probably because the spec text is a little hard to read, but it adds an important bit of behaviour:

An <img> is a "replaced element", but it doesn't have a "natural aspect ratio" until the browser has loaded enough of the image to know its real width & height. That means the 16 / 9 bit is ignored once the browser has the real data from the image. This doesn't usually matter, because the result is the same. But, let's say I got the width and height wrong:

The browser will use an presentational hint of aspect-ratio: auto 4 / 3 , but the image is actually 16 / 9 . Here's what happens:

When the image is added to the page, it takes up the 4 / 3 area I specified. But once it loads, the auto rule kicks in, and the browser corrects the aspect ratio to 16 / 9 .

Compare this to the behaviour of:

Without auto , the <img> remains 4 / 3 , and the image appears stretched. You can avoid the stretching with object-fit :

In this case, parts of the image are cropped. Oh, one more thing:

A slight issue in Firefox

Responsive images let you provide different images to use at different widths:

In this case, the two images have different aspect ratios. Chrome and Safari use the correct width and height depending on which source is used, but Firefox will always use the dimensions from the <img> , resulting in a content shift when it realises the calculated aspect-ratio is incorrect.

Here's the Firefox bug to track this. Hopefully it'll get fixed soon!

So, which method should we use?

Ok, until now the article has been a massive side-quest. Now we're at the actual point. And, in my opinion, the answer is… nothing new.

We've got one solution, aspect-ratio , which is CSS-based. And the other solution, presentational hinting, which uses width and height attributes. The question is very similar to "should this image be a <img> or a CSS background-image ?" and the answer is the same: Is it content or design?

If I'm adding an image to an article on my blog, that's content. I want the reserved space to be the aspect ratio of the content. If I get the width and height attributes wrong, I'd rather the correct values were used from the content image. Therefore, width and height attributes feel like the best fit. This means I can just author content, I don't need to dip into inline styles.

If it's a design requirement that the layout of an image is a particular aspect ratio, enforcing that with aspect-ratio in CSS can be appropriate. For example, a hero image that must be 16 / 9 – if the image isn't quite 16 / 9 I don't want it messing up my design, I want the design to take priority. Although, if the image isn't actually that aspect ratio, it'll either end up stretched ( object-fit: fill ), letter-boxed ( object-fit: contain ), or cropped ( object-fit: cover ). None of which are ideal.

You could use aspect-ratio and media queries to make up for the lack of support in Firefox when it comes to <picture> and art direction. But, I'm hoping that they'll fix that bug sooner rather than later, so we don't need to hack around it.

And that's it! It took a decade for us to get a real solution to this problem, but now you can avoid layout shifts using width and height attributes, or aspect-ratio in CSS, whichever is most appropriate.

View this page on GitHub

Hello, I'm Jake and that's me there. The one that isn't a cat. I'm a developer of sorts.

Feel free to throw me an email , unless you're a recruiter, or someone trying to offer me 'sponsored content' for this site, in which case write your request on a piece of paper, and fling it out the window.

  • Español – América Latina
  • Português – Brasil
  • Tiếng Việt

New aspect-ratio CSS property supported in Chromium, Safari Technology Preview, and Firefox Nightly

The new CSS property that helps maintain spacing in responsive layouts.

Una Kravets

Aspect ratio

Browser Support

Aspect ratio is most commonly expressed as two integers and a colon in the dimensions of: width:height, or x:y. The most common aspect ratios for photography are 4:3 and 3:2, while video, and more recent consumer cameras, tend to have a 16:9 aspect ratio.

Two images with the same aspect ratio. One is 634 x 951px while the other is 200 x 300px. Both have a 2:3 aspect ratio.

With the advent of responsive design, maintaining aspect ratio has been increasingly important for web developers, especially as image dimensions differ and element sizes shift based on available space.

Some examples of where maintaining aspect ratio become important are:

  • Creating responsive iframes, where they are 100% of a parent's width, and the height should remain a specific viewport ratio
  • Creating intrinsic placeholder containers for images, videos , and embeds to prevent re-layout when the items load and take up space
  • Creating uniform, responsive space for interactive data visualizations or SVG animations
  • Creating uniform, responsive space for multi-element components such as cards or calendar dates
  • Creating uniform, responsive space for multiple images of varying dimension (can be used alongside object-fit )

Defining an aspect ratio helps us with sizing media in a responsive context. Another tool in this bucket is the object-fit property, which enables users to describe how an object (such an as image) within a block should fill that block:

Object-fit demo visualization

The initial and fill values re-adjust the image to fill the space. In our example, this causes the image to be squished and blurry, as it re-adjusts pixels. Not ideal. object-fit: cover uses the image's smallest dimension to fill the space and crops the image to fit into it based on this dimension. It "zooms in" at its lowest boundary. object-fit: contain ensures that the entire image is always visible, and so the opposite of cover , where it takes the size of the largest boundary (in our example above this is width), and resizes the image to maintain its intrinsic aspect ratio while fitting into the space. The object-fit: none case shows the image cropped in its center (default object position) at its natural size.

object-fit: cover tends to work in most situations to ensure a nice uniform interface when dealing with images of varying dimensions, however, you lose information this way (the image is cropped at its longest edges).

If these details are important (for example, when working with a flat lay of beauty products), cropping important content is not acceptable. So the ideal scenario would be responsive images of varying sizes that fit the UI space without cropping.

The old hack: maintaining aspect ratio with padding-top

Using padding-top to set a 1:1 aspect ratio on post preview images within a carousel.

In order to make these more responsive, we can use aspect ratio. This allows for us to set a specific ratio size and base the rest of the media on an individual axis (height or width).

A currently well-accepted cross-browser solution for maintaining aspect ratio based on an image's width is known as the "Padding-Top Hack". This solution requires a parent container and an absolutely placed child container. One would then calculate the aspect ratio as a percentage to set as the padding-top . For example:

  • 1:1 aspect ratio = 1 / 1 = 1 = padding-top: 100%
  • 4:3 aspect ratio = 3 / 4 = 0.75 = padding-top: 75%
  • 3:2 aspect ratio = 2 / 3 = 0.66666 = padding-top: 66.67%
  • 16:9 aspect ratio = 9 / 16 = 0.5625 = padding-top: 56.25%

Now that we have identified the aspect ratio value, we can apply that to our parent container. Consider the following example:

We could then write the following CSS:

Maintaining aspect ratio with aspect-ratio

Using aspect-ratio to set a 1:1 aspect ratio on post preview images within a carousel.

Unfortunately, calculating these padding-top values is not very intuitive, and requires some additional overhead and positioning. With the new intrinsic aspect-ratio CSS property , the language for maintaining aspect ratios is much more clear.

With the same markup, we can replace: padding-top: 56.25% with aspect-ratio: 16 / 9 , setting aspect-ratio to a specified ratio of width / height .

Using aspect-ratio instead of padding-top is much more clear, and does not overhaul the padding property to do something outside of its usual scope.

This new property also adds the ability to set aspect ratio to auto , where "replaced elements with an intrinsic aspect ratio use that aspect ratio; otherwise the box has no preferred aspect ratio." If both auto and a <ratio> are specified together, the preferred aspect ratio is the specified ratio of width divided by height unless it is a replaced element with an intrinsic aspect ratio, in which case that aspect ratio is used instead.

Example: consistency in a grid

This works really well with CSS layout mechanisms like CSS Grid and Flexbox as well. Consider a list with children that you want to maintain a 1:1 aspect ratio, such as a grid of sponsor icons:

Example: preventing layout shift

Another great feature of aspect-ratio is that it can create placeholder space to prevent Cumulative Layout Shift and deliver better Web Vitals . In this first example, loading an asset from an API such as Unsplash creates a layout shift when the media is finished loading.

Using aspect-ratio , on the other hand, creates a placeholder to prevent this layout shift:

Bonus tip: image attributes for aspect ratio

Another way to set an image's aspect ratio is through image attributes . If you know the dimensions of the image ahead of time, it is a best practice to set these dimensions as its width and height .

For our example above, knowing the dimensions are 800px by 600px, the image markup would look like: <img src="image.jpg" alt="..." width="800" height="600"> . If the image sent has the same aspect ratio, but not necessarily those exact pixel values, we could still use image attribute values to set the ratio, combined with a style of width: 100% so that the image takes up the proper space. All together that would look like:

In the end, the effect is the same as setting the aspect-ratio on the image via CSS, and cumulative layout shift is avoided ( see demo on Codepen ).

With the new aspect-ratio CSS property, launching across multiple modern browsers, maintaining proper aspect ratios in your media and layout containers gets a little bit more straightforward.

Photos by Amy Shamblen and Lionel Gustave via Unsplash.

Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License , and code samples are licensed under the Apache 2.0 License . For details, see the Google Developers Site Policies . Java is a registered trademark of Oracle and/or its affiliates.

Last updated 2021-01-28 UTC.

Navigation Menu

Search code, repositories, users, issues, pull requests..., provide feedback.

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly.

To see all available qualifiers, see our documentation .

  • Notifications

Select auto width in Safari #326

@eugeniojauregui

eugeniojauregui commented Apr 26, 2013

@fidian

fidian commented Jun 4, 2013

Sorry, something went wrong.

eugeniojauregui commented Jul 9, 2013

@jeffclemens

jeffclemens commented Jul 19, 2013

@roubaobaozi

roubaobaozi commented Jul 31, 2013

@adibreaban

adibreaban commented Jan 27, 2014

Roubaobaozi commented jan 30, 2014, adibreaban commented jan 30, 2014, roubaobaozi commented jan 31, 2014, adibreaban commented jan 31, 2014, roubaobaozi commented apr 3, 2014.

@gandoulfe

gandoulfe commented Jun 6, 2014

Roubaobaozi commented jun 12, 2014.

@shehi

fidian commented Jun 20, 2016

No branches or pull requests

@fidian

[Resolved] Fullwidth area not working in Safari

Home › Forums › Support › [Resolved] Fullwidth area not working in Safari

Popular Articles

  • Missing style.css

Updating errors

  • Installing GP Premium

Installing GeneratePress

How to add CSS

How to add PHP

Home › Forums › Support › Fullwidth area not working in Safari

' src=

  • Author Posts

' src=

This ist not really a support question. It might be beyond the scope of a support forum. I fully understand if you can’t take the time to answer it. However, since you are so good with CSS, I have some hope. 🙂

I pretty often use fullwidth sections on pages that have a boxed layout like on this page (the large blue section below the grid):

https://www.agoshop.de/

(It is intended that the background does not cover the whole image at the bottom.)

David kindly helped me out with this CSS, which works perfectly fine:

This is the entire CSS for the section:

Now, I’ve just found out that Safari has some problems. It shows a white empty space on the right side like so:

safari image width auto not working

Safari 15 with OS 15 or 10.15 seems to be the only combinations that does not mess up the CSS. In Windows it works fine on pretty much all devices and browsers apart from Internet Explorer. But I couldn’t care less about IE.

Since I don’t have Apple devices, it is very difficult to troubleshoot. Any help would be very much appreciated.

' src=

you can try adding: max-width: 100vw; property to your .fullwidth-banner CSS But this CSS Hack is a little bit hit and miss and different browsers on different OSs may have an issue with it. Normally Chromium browsers on Windows has an issue with it.

My personal approach would be to make the Page Full Width, and then contain the sections that i want to keep contained…

Thank you for pointing me in the right direction. It turned out that it’s not the width part causing the trouble, but the background size part. It seems that Safari on desktop and both Chrome and Safari on mobile don’t like this CSS:

background-size: auto calc(100% - 90px);

Removing it removes the problem. I have no idea how to fix this, since the combination of relative and absolute height is needed here to make it fully responsive.

I could probably put the image outside the blue section and do something like this:

Should work, but it’s not very clean CSS, I guess. Would you consider this acceptable?

I think, I’ve just found out what the issue is. Safari and Chrome/iOS seem not to understand the “auto” value in

background-size: auto ...

It seems to work after changing it to:

background-size: 100% calc(100% - 90px);

Is it working correctly now ?

as much as I can see, yes. It seems that the “auto” value for the background size is not working in Safari.

Thats very odd especially as its affecting the container overflow. I may have to do some investigating.

Let me know, if I can help somehow. Unfortunately, troubleshooting is quite tedious for me without any Apple devices. I have to go to the local Apple store for testing the results. Lambdatest does quite a good job for desktop, but is not very reliably for mobile devices.

I’ve just set up two static html pages that contain only the needed HTML and CSS:

This page uses the “auto” value.

This page uses the “100%” value.

According to Lambdatest, only the second page is rendered correctly in Safari.

Yeah – Safari renders it differently to Chrome for sure. Its maintaining aspect ratio of the background. Whereas other browers are stretching them. So hard to say if Safari is wrong or right – as its a different interpretation of the spec.

This light reading ( lol 🙂 ) on the property may provide some insight to what its doing as specs vary across browsers:

https://developer.mozilla.org/en-US/docs/Web/CSS/background-size#intrinsic_dimensions_and_proportions

and particularly on Gradients:

https://developer.mozilla.org/en-US/docs/Web/CSS/background-size#working_with_gradients

But it seems you found the solution using 100% instead of auto which is logically correct.

Thank you, David. Interesting. It seems that the combination of auto and a pixel value is not safe. Let alone a combination of auto and calc, I guess. Changing auto to a percentage value was really just trial and error.

These are the pleasures of recreating a design properly that was formerly made using a crappy visual editor. 🙂

I kind of hope for the day that all browsers interpret CSS in the same way. But then we wouldn’t have these amusing anecdotes to keep our web developing fun 🙂

Nice find. Thanks for sharing.

But then we wouldn’t have these amusing anecdotes to keep our web developing fun

Nicely put, David! 🙂

On the other hand, working with CSS has been so much harder 10 years ago. I look at you, Internet Explorer! Nowadays, results are quite consistent, if you avoid cutting edge CSS.

Having said this, Microsoft is still a reliable source of frustration, if you have to create HTML emails that work in Outlook. 🙂

Thanks again for your generous help. This was really a hard nut to crack.

Glad to be of some help 🙂

  • You must be logged in to reply to this topic.

Start building better websites today.

GeneratePress

  • Site Library
  • Brand Assets
  • We’re Hiring!
  • Documentation
  • Support Forums
  • Archived Support Forums
  • Fastest WordPress Theme
  • Install GeneratePress
  • Plugin Install Failed
  • WordPress Hosting

© 2024 EDGE22 Studios LTD.

CSS Grid not display correctly in Safari

I have a couple of CSS Grid elements and they display perfectly in Chrome and Firefox, however when in Safari they are all messed up. I have tried some of the solutions shown in other posts but nothing has worked. The grid is also not working right in Safari on iPad but is fine on iPhone. What’s up with THAT?

Here is my site Read-Only: **[ https://preview.webflow.com/preview/kelly-hoopers-website?utm_medium=preview_link&utm_source=designer&utm_content=kelly-hoopers-website&preview=de6225062126e07a94a005cb2d8a3aa8&pageId=608709fce1d822a9235430e9&mode=preview

CSS grid is not fully supported by all browsers. What version of Safari are you using? This page shows which browsers support CSS grid and which browser versions do not support CSS grid. Also, if you look at the known issues tab on the “Can I Use” page it says “Safari does not yet support intrinsic and extrinsic sizing with grid properties such as `grid-template-rows’”.

hi @freedj I have looked on your issue and your problem is with settings of container 12 and grid images height. All you have to do is to set container 12 to block and images height to auto . Here is a short video how to do that.

https://cln.sh/7e5RdN

AMAZING! Thank you!!

I have this problem too but can’t seem to work out how to fix it. On the homepage I have a testimonial section which breaks on Safari, also using a grid. Can anyone help?

Read only link: https://preview.webflow.com/preview/earthfound?utm_medium=preview_link&utm_source=designer&utm_content=earthfound&preview=610dcbf4d7d396411512e3b3cd157507&workflow=preview

I also had a problem with a grid in Apple Safari and found out it had to do with: Grid > Distribute. I changed this to: Grid > Distribute > Content Start and now it is displayed properly.

Maybe you can do something with it.

IMAGES

  1. Safari Not Working On iPhone? Here's The Fix. [Step-By-Step Guide]

    safari image width auto not working

  2. How to set up an image as your Home page in Safari on Mac

    safari image width auto not working

  3. Image Component not working on MacOS Safari · Issue #19038 · vercel

    safari image width auto not working

  4. How to adjust the resolution in Safari?

    safari image width auto not working

  5. Why Are Images Not Showing Up in Safari on My Mac?

    safari image width auto not working

  6. Why Are Images Not Showing Up in Safari on My Mac?

    safari image width auto not working

VIDEO

  1. How To Fix Safari Could Not Install A Profile Due To An Unknown Error 2024|iphone|Iped

  2. Android Auto not working

  3. power window auto not working

  4. CarPlay or Android Auto not working

  5. How to enter full screen in Safari

  6. Safari Could not install a profile due to an unknown error in iPhone iPad Problem Fix

COMMENTS

  1. Set image height to 100% and width to auto not working in Safari

    The problem is it being a text image, so I need it to stay in a certain width and only depend on height. If I put 100% width and height auto, it will be really large.... - HannesH. Mar 31, 2014 at 13:08. Then try the image at 50% then it will always be half, I would suggest playing arround with the percentages because with width being auto ...

  2. Safari Image Size Auto Height CSS

    I am testing this problem in the latest version of Safari for Windows 7. The problem is that this code works in all other browsers BUT safari: <style type="text/css"> .userImg { height...

  3. Safari not computing image aspect ratios from width and height

    I fixed the problem by manually specifying the image dimensions using the `width` and `height` image attributes, as below: ... in Safari, the space is not reserved and the page shifts after the image is loaded. Here's a CodePen example ... The only tangible difference in code there is the use of `data-sizes="auto"`, which shouldn't make any ...

  4. Setting Height And Width On Images Is Important Again

    Working Around The Problem. The limitations for responsive images have been known for a long time and many workarounds, including the so-called padding-bottom hack, have been created to work around the issue.This uses the fact that padding percentages (including padding-bottom) are always based on the container width (to ensure a consistent padding even if height and width differ).

  5. Safari not computing image aspect …

    Safari not computing image aspect ratios from width and height attributes. I've recently implemented a lazy image loading feature on an image-heavy website, and have been having issues with reflow. I fixed the problem by manually specifying the image dimensions using the width and height image attributes, as below: It works great in every ...

  6. Responsive Image Height different under safari and chrome and ...

    Under chrome and firefox all the images in this grid are of equal height, however, in Safari, there are two images (Napa & SLD Residence) whose height is 600pixels instead of 358px. The images are coming from a CMS. When I had uploaded the images into the CMS to be used as thumbnails, these were all uploaded as 800x600pixels and heavily ...

  7. Safari not computing image aspect ratios from width and height ...

    I fixed the problem by manually specifying the image dimensions using the width and height image attributes, as below: ... in Safari, the space is not reserved and the page shifts after the image is loaded. Here's a CodePen example with near identical code to mine (you should open in Safari and click immediately on "Nav 4" to see the issue ...

  8. Safari not computing image aspect ratios from width and height ...

    I fixed the problem by manually specifying the image dimensions using the width and height image attributes, as below: It works great in every browser except Safari, but I'm confused because Safari 14 supposedly supports computing aspect ratios based on the width and height attributes . None of my up-to-date macOS or iOS devices seem to ...

  9. How to Fix CSS Issues on Safari

    To make it work on Safari, we must set the appearance property to its "none" value. Also, use -WebKit- and -Moz- vendor prefixes. Let's see an example, where we use this trick to make the border-radius property work on Safari without any problem. height: 100px; width: 17%;

  10. Avoiding layout shifts: aspect-ratio vs width & height attributes

    The new bit is auto.Here's what the spec says: If both auto and a <ratio> are specified together, the preferred aspect ratio is the specified ratio of width / height unless it is a replaced element with a natural aspect ratio, in which case that aspect ratio is used instead. — CSS-sizing level 4 A lot of articles gloss over this, probably because the spec text is a little hard to read, but ...

  11. Workaround for aspect-ratio on Safari

    The height will be 384 * 16 / 9 = ~682.66px. However, it doesn't work on most versions of Safari iOS. So my workaround is to calculate it dynamically using JS below: Basically what I do here is to set a ref to the div element I want to apply the aspect-ratio and get the width or height then do the math. I need one of the dimensions to ...

  12. Browser-level image lazy loading for the web

    These images might be behind a carousel or hidden by CSS for certain screen sizes. For example, Chrome, Safari, and Firefox don't load images using display: none; styling, either on the image element or on a parent element. However, other image hiding techniques, such as using opacity:0 styling, still cause the browser to load the image. Always ...

  13. Images with max-height property do not resize correctly

    So I took a minute to search for Safari specific fixes and it appears that the browser should do a good job of scaling images proportionally if you set a width but keep the height set to Auto.. I tried the fix in DevTools on your staging site but was still getting a similar problem where they weren't growing accordingly—but only after they reached a certain size.

  14. Safari messes up scaling of images in grid

    I'm working on a site and everything worked fine so far. Recently I checked the site in Safari to test responsiveness etc. but Safari completely messes up the scaling of images positioned in grids (with a size of 100%). It's very important to me not to set a specific size in pixels, cause my idea is to always fill the space provided by the ...

  15. css

    146. It certainly appears to be a bug. The default setting for the align-items property is stretch. Most major browsers handle this sensibly, stretching the image within the confines of the container. For whatever reason, Safari stretches the image to its natural height, taking the container along for the ride.

  16. New aspect-ratio CSS property supported in Chromium, Safari Technology

    Note: Summary: Maintaining a consistent width-to-height ratio, called an aspect ratio, is critical in responsive web design and for preventing cumulative layout shift.Now, there's a more straightforward way to do this with the new aspect-ratio property launching in Chromium 88, Firefox 87, and Safari Technology Preview 118. Aspect ratio

  17. Select auto width in Safari · Issue #326

    It looks like the problem is that the width of the entire box is wider on all other browsers than that of Safari on Windows (in the case of uniformjs.com, in Chrome the "Option 1" select box is 99px wide, while in Safari it is 76px wide.) Adding -webkit-appearance: none; to Safari through Inspector doesn't change that.

  18. Image width does not change proportionally in Safari

    Also updating to change the image size instead of the container size works. So, instead of having the image stretch to fill the div size (which the width of the div isn't changing so it makes some sense that the width of the image wouldn't change either), you can change the image size and have the div stretch to contain the image, like so:

  19. Fullwidth area not working in Safari

    Thank you for pointing me in the right direction. It turned out that it's not the width part causing the trouble, but the background size part. It seems that Safari on desktop and both Chrome and Safari on mobile don't like this CSS: background-size: auto calc(100% - 90px); Removing it removes the problem.

  20. responsive image not working on safari mac and safari iPhone

    im making a website, but the responsive image for safari mac/iphone is not working here is my code ... figure img { display: block; width: 100%; height: auto; max-width: 100%; /* just in case? not nessesary */ } .logo { /* specific figure size */ max-width: 400px; }

  21. CSS Grid not display correctly in Safari

    ikeholland (Ike van Gerven) December 1, 2023, 8:35pm 6. I also had a problem with a grid in Apple Safari and found out it had to do with: Grid > Distribute. I changed this to: Grid > Distribute > Content Start and now it is displayed properly. Maybe you can do something with it. I have a couple of CSS Grid elements and they display perfectly in ...