Danmoreng
Danmoreng

Reputation: 2367

Browser detect actual image size needed

When using the picture tag with srcset, I can define different image sources for different viewport widths.

What I want however, is to define different images sources for the actual space (width-based) the image occupies after the browser has rendered the page.

For example:

  1. Viewport width is 1920px Website uses container size of 1200px

  2. Container is split into two columns of 600px each

  3. Column 2 contains an image with 100% width - which will result in a width of 600px
  4. The srcset for the image supplies 400x300px, 800x600px and 1200x900px
  5. The browser should now automatically know to pick 800x600px

As long as it's clear that the image will always be in that spot, I could use srcset based on the viewport width.

Unfortunately, my site design is so, that content editors can freely add columns/rows and even nest them. Also at some point columns collapse and become always full-width. So when rendering the HTML, I cannot predict how much of the viewport width an image will get.

Therfor I would love to have the browser check how much pixels the image actually has when it's rendered to the user - and choose the appropiate image.

I have searched quite a bit, but couldn't find anything about that.

Is that even possible?

Or is the only solution a Javascript one?

Upvotes: 1

Views: 104

Answers (1)

elveti
elveti

Reputation: 2386

No, sadly this is not possible yet. There has been much talk about element queries, basically media queries that apply to the element's size, instead of the windows size. But they are apparently really complicated to integrate. There is also no syntax for it yet. The classic problem that is often brought up (in pseudo-syntax), is something like this:

.child {
  width: 500px;
}
.container:min-width(450px) > .child {
  width: 400px;
}

so we set .child to 500px width, BUT then we say if the child's parent is more than 450px, the .child should have a width of 400px, thus .container would be less than 450px again, and .child is set again to 500px and so on and on. This causes what is called a "circularity problem".

There are also other problems, such as with dynamic layouts and the browser not really knowing how much space an element will take up beforehand. This could lead to huge performance issues, as the browser would simply have to calculate too much.

There are however JS libraries that try to implement this (e.g. EQCSS, CSS-Element-Queries or EQJS), but for your case a selfmade JS would probably be better. I'd recommend checking out how those libraries handle it though.

More info:

https://www.xanthir.com/b4PR0

https://webdesign.tutsplus.com/articles/the-current-state-of-element-queries--cms-29690

JS Libraries:

https://elementqueries.com/

http://marcj.github.io/css-element-queries/

https://github.com/snugug/eq.js

Upvotes: 1

Related Questions