diff options
author | Sangeeth Sudheer <git@sangeeth.dev> | 2025-03-16 08:37:22 +0530 |
---|---|---|
committer | Sangeeth Sudheer <git@sangeeth.dev> | 2025-03-26 07:39:37 +0530 |
commit | 8e50f5c421b5b44ad33e325e67efc92c64264e72 (patch) | |
tree | eb704099222fad3702748cc18ee4e4de6d3ced62 | |
parent | 361e58e6660b646eb56a538f8840cccabcc01fed (diff) |
Fix layout shifts by preserving aspect-ratio at responsive sizes
Uses `aspect-ratio` property to constrain height and width of render image's container to allow responsive resizing
while maintaining the original aspect ratio and avoiding layout shifts.
Previously, even though `width` and `height` attributes were passed to the `img` element, Chrome (and probably others)
weren't reserving space for the image as expected because CSS `width`/`height` were both `auto`. At least one of them
needed to be a fixed value in order to maintain aspect ratio. Even with this change, it doesn't seem possible to
constrain both width and height on the same element at the same time — only one or the other works.
The change introduced makes the `img` element constrain width using `max-width` while the parent element constrain
height using `max-height` and `aspect-ratio`. This way, we can get responsive sizing on both axes while obeying the
constraints.
-rw-r--r-- | assets/css/main.css | 23 | ||||
-rw-r--r-- | layouts/_default/_markup/render-image.html | 2 |
2 files changed, 13 insertions, 12 deletions
diff --git a/assets/css/main.css b/assets/css/main.css index 6e83511..033e3cc 100644 --- a/assets/css/main.css +++ b/assets/css/main.css @@ -440,18 +440,19 @@ footer a { /* images */ -figure>div { - width: 100%; - display: flex; - justify-content: center; -} +figure { + .img-container { + aspect-ratio: var(--w) / var(--h); + max-height: var(--figure-img-max-height); + width: auto; + margin-inline: auto; + } -figure img { - max-width: 100%; - max-height: var(--figure-img-max-height); - width: auto; - height: auto; - margin-inline: auto; + img { + display: block; + max-width: 100%; + height: auto; + } } .dark .img-light { diff --git a/layouts/_default/_markup/render-image.html b/layouts/_default/_markup/render-image.html index e6a5c39..a1bc158 100644 --- a/layouts/_default/_markup/render-image.html +++ b/layouts/_default/_markup/render-image.html @@ -46,7 +46,7 @@ and build the img class string as "img-tag1 img-tag2 ..." {{/* Use the computed classes on the rendered figure */}} <figure class="{{ $classes }}"> - <div> + <div class="img-container" {{ with $imgResource }}style="--w: {{ .Width }}; --h: {{ .Height }};"{{ end }}> <img loading="lazy" alt="{{ .Text }}" src="{{ $url }}" {{ with $imgResource }}width="{{ .Width }}" height="{{ .Height }}"{{ end }}> </div> |