Skip to content

[Proposal] Support styling based on an element’s intrinsic aspect ratio (or size) #12197

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
7devv opened this issue May 15, 2025 · 1 comment

Comments

@7devv
Copy link

7devv commented May 15, 2025

In many real-world layouts, especially in e-commerce and gallery systems- images vary significantly in their intrinsic dimensions. For example, some product images are tall and narrow, while others (like room scenes or banners) are wide or square. Depending on the shape, different styling is appropriate.

A common case is controlling object-fit behavior. Wide or square images often look good with object-fit: cover, while narrow or tall images can get awkwardly cropped and instead need object-fit: contain.

There’s currently no way in CSS (that I'm aware of) to style an element differently based on its intrinsic aspect ratio (natural width and height). This makes it difficult to build responsive, robust layouts without relying on JavaScript to measure images and inject classes conditionally.

Here's a codepen to help visualize: Product Grid Demo

What doesn't work:

  • @media (aspect-ratio) only applies to the viewport, not the element
  • aspect-ratio as a property only defines a preferred aspect ratio; it doesn’t expose the intrinsic ratio
  • Container queries work based on the parent/container size, not the intrinsic size of the element
  • :has() and other selectors can’t introspect natural dimensions

Why this matters:

Being able to style based on intrinsic aspect ratio would allow developers to handle layout logic that depends on the content shape, without using JavaScript. It's a purely presentational concern that feels like it should be solvable with CSS, but currently isn't.

I’m not sure what the right implementation path is (e.g. pseudo-class, query, or something else), but would like to open the conversation to see if this kind of feature is feasible or already being/been explored. If there is a way to do this without conditionally applying classes with JS and applying style overrides, please enlighten me, I am very curious about this!

@7devv
Copy link
Author

7devv commented May 15, 2025

I found another example to further iterate on this: Reddit post

Really hoping we can do this in the future with CSS

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant