11 ms·
Aspect-ratio is great
- Tomte 5y agoIf you just want this to avoid layout shift, you're still better off using explicit width and height attributes (on the img tag), because it is per-image in the HTML itself, not in a common CSS declaration. Is that right?
- fleddr 5y agoRegardless of whether you use this CSS rule or not, it's a best practice to ALWAYS set the width and height attributes of any image. So even if you use this CSS rule, you should also set those width and height attributes. This allows the browsers to draw the correctly sized box whilst the image is still loading and whilst CSS hasn't kicked in yet.
- wruza 5y agoArticles like that always make me smile, because I imagine like 20 years ago someone would write a lenghty blog post about GtkAspectFrame or GtkHBox and its “expand” and “fill” child properties. Or about GtkSizeGroup (which css still can’t figure out). Gtk is awesome, so amazing!
- crancher 5y agoThis will save thousands and thousands of designer/developer/producer hours.
- Waterluvian 5y agoOh my god. I spent so freaking much time trying to solve “make the outermost div fill the screen of the device but always keep it a specific ratio.” Hours and hours. And hours.
- lelandfe 5y agoThe old answer, for those curious, was a padding-bottom with the aspect ratio expressed as a percentage: https://jsfiddle.net/9yLkm0tu/ https://jsfiddle.net/9yLkm0tu/ This works because padding percentages are calculated based on width – making this, at the time, the only practical way to form a relationship between an element's height and width. Thierry Koblentz coined this "intrinsic ratios" back in '09: https://alistapart.com/article/creating-intrinsic-ratios-for-video/ https://alistapart.com/article/creating-intrinsic-ratios-for... Some people call it a hack – it's just a narrow application of the spec.
- robgibbons 5y agoBack in the day my trick was to use a transparent PNG of just a few pixels in each dimension to establish an aspect ratio for a fluid-width div.
- Cthulhu_ 5y agoThat reminds me of using images for rounded corners, used for years until CSS supported them; then they went out of fashion for a while, lol.
- arecurrence 5y agoThis has been one of my absolute favorite CSS improvements in recent years. Upon first seeing it people don't typically pick up on the magnitude of benefit that the feature offers. Once it sets in, however, you start seeing it everywhere. Image dimension management had been an enduring problem throughout CSS history but now aspect ratio is supported across the board https://caniuse.com/mdn-css_properties_aspect-ratio https://caniuse.com/mdn-css_properties_aspect-ratio.
- christophilus 5y agoOh, man. Last time I looked, it wasn’t supported in a handful of browsers I cared about. Now it is. I’m ripping out some hacky CSS tomorrow!
- Crazyontap 5y agoThis is really amazing. The last CSS thing I learned about was flex-box and it so vastly improved my side projects. I'm sure this will come quite handy too. What are more such things which you love about CSS but only learned about recently? Can greatly benefit CSS dinosaurs like me who know CSS but haven't really kept up on the recent developments.
- city41 5y agoinset is a handy shortcut. https://developer.mozilla.org/en-US/docs/Web/CSS/inset https://developer.mozilla.org/en-US/docs/Web/CSS/inset
- Swizec 5y agoLook into grid. It’s like flexbox on steroids – 2D positionint instead of 1D. <div> hell just melts away
- lelandfe 5y agoSometimes you want to change things on touch input devices - thumbs are quite bigger than cursors. Here's a tidy way to do that: .foo-component { --size: 20px; width: --size; height: --size; @media (hover: none) { --size: 40px; } }
- micromacrofoot 5y agounfortunately this is a little unreliable for detecting touch screen laptops
- afavour 5y agoYes, the correct way (these days) to detect what the OP actually wants is the pointer media query: https://davidwalsh.name/pointer-media-query https://davidwalsh.name/pointer-media-query Which has values for coarse (finger) and fine (mouse, tablet, etc)
- 5y ago
- runarberg 5y agoI have used aspect-ration in production and I concur. Say you want to display a user avatar, but the user might not have uploaded their avatar, so you fallback with a colored box (basically a div) with the user’s initials instead (or—in practice—your best guess of their initials). aspect-ratio will cover both of these. So you can you don’t need to set a different weight or padding depending of if you have an image or a div.
- c-smile 5y agoaspect-ratio is actually a great mistake - it breaks CSS box model again (after flexbox). What should be the dimensions of this div { width:100px; height:100px; aspect-ratio: 3 / 2; } ? Instead, there should be "functions" width(N%) and height(N%) and so div { width:100px; height: width(66%); } div { height:100px; width: height(150%); } div { height:40px; line-height: height(100%); } div { width:100px; margin: width(10%); } Therefore, instead of one more property that "solves" only one particular problem we will have bunch of solutions by adding just two pseudo-functions. And without breaking box model in very nasty way. For that matter, Sciter (https://sciter.com https://sciter.com) has these width()/height() functions 10 or so years already.
- lelandfe 5y ago`aspect-ratio` specifies the preferred ratio. It gets used in cases where sizing values are intrinsic. In your first example, it would be overruled by the defined sizing values. I think that's fine, personally. Further, I don't see how it breaks the box model – esp. given that the spec that defines box model also defines `aspect-ratio`
- c-smile 5y agoWhat if you have that width and aspect-ratio defined and in "galaxy far, far away" someone will define height for that element? What about good old principle of least astonishment? Not for us anymore? That's the problem - instead of two properties that define box dimensions you now have now who knows how many props changing dimensions Why the hell property named align(sic!) `align-items: stretch;` shall change box dimensions? And what to do with width/height then?
- AprilArcus 5y agoDon't expose your CSS classes to spooky action at a distance. Use a build system or CSS in JS library to hash your class names and keep them private. It's a terrible shame that CSS relies so heavily on globals (I'm looking at you, `@keyframes`), but as programmers we should all recognize them when we see it and avoid them by any means possible.
- rado 5y agoYes, until you realise it messes up sub pixel calculations, unlike the padding hack…
- r_hoods_ghost 5y ago"The text content in the third box is longer than the available space, so rather than maintaining the aspect ratio, the element expands vertically to fit the content... If we set an explicit height instead, the element doesn’t expand, but instead we get overflow" Why? Why would you have different default behaviours if you have one of the dimensions set but not the other? Why would you not have this specified in another property, the overflow property perhaps? Oh look, lets define a new property and call it aspect ratio, and then lets ensure it doesn't maintain an element's aspect ratio if you have content that is going to overflow if you specify a width. This is what drives me mad about css, it's gotchas all the way down.
- selfmodruntime 5y agoYea, this is an insane overlook in the spec
- eyelidlessness 5y ago> Why would you have different default behaviours if you have one of the dimensions set but not the other? Basically: be there or be square (fill up the space or not, your choice), but if you show up there’s a dress code (you can only fill up the space as specified). > Oh look, lets define a new property and call it aspect ratio, and then lets ensure it doesn't maintain an element's aspect ratio if you have content that is going to overflow if you specify a width. This is what drives me mad about css, it's gotchas all the way down. There’s a lot I don’t like about CSS, but this is just the spec avoiding undefined behavior. No one is using aspect ratio for unbounded text in practice, they’re using it for media or a design system. Knowing how it behaves for edge cases is much better than having a protracted battle for years while vendors sort it out, with different assumptions in the wild.
- jontro 5y agoIf you set overflow: hidden it seems to do the trick on chrome at least
- eyelidlessness 5y ago
- lhball 5y agoGood read. It’s kinda funny that, on a CSS focused site, the position of the “latest” article label on the homepage is set above that of the site logo and navigation bar. It’s nice to know even CSS experts make mistakes ¯\_(ツ)_/¯.
- eyelidlessness 5y agoI’m reading on iOS Safari so maybe not seeing what you’re seeing, but I don’t see what you describe.
- lhball 5y agoLate to this. Here’s a screen shot. https://imgur.com/a/gYLytqh https://imgur.com/a/gYLytqh
- eyelidlessness 5y agoOh I see it, classic off by z-index error.
- baxuz 5y agoNot really. It's still tied to the element's width and will overflow vertically. Even if using a flex/grid container with a different axis, it will only constraint the aspect ratio to its width. Which means that if you want to have something like a video player in the viewport like YouTube does, or lightbox-style previews which keep the entire media element in viewport you'll still have to use JS to limit the element's height, or if the design allows for it, use viewport height units + calc.
- _def 5y agoI'm so happy to see directives like these making it into css! It's great to have super granular control of every dimension and stuff, but in terms of creating layouts etc it really needs higher abstraction properties like this. I think this is why css was always so frustrating for me: caring about the technical side of things instead of the actual design implementation, which I now realize is not entirely my fault, but rather by design of the sepcs. (I still need to learn about layout fundamentals etc, but this certainly helps getting a grasp of things)
- supernes 5y agoI was under the impression that this has been a thing for a long while, but I checked and it's actually been available in mainstream browser versions only since January 2021 (September for Safari, and just nine days ago for Chrome on Android). Combined global usage for supported platforms is around 84%. https://caniuse.com/mdn-css_properties_aspect-ratio https://caniuse.com/mdn-css_properties_aspect-ratio
- dep_b 5y agoI've stopped working on web projects about ten years ago and it's still shocking how much was missing from even the most basic things compared to other UI frameworks that often had it for decades. It's quite sad that there's apparently no other direction than "JavaScript and the web will replace every type of application eventually". I mean look how well Microsoft Word (native) works compared to Microsoft Teams (some JS hodgepodge). And not just the day by day use, but also stuff like AppleScript support. Especially highlighted by the stand still we used to have on mobile computer CPU's until recently. Everything just got slower and slower.
- divan 5y agoThank you for this comment. It's scary to think that majority of the tech-savvy people in the world never question sanity of web stack and don't see how badly it is unfit for making UI apps. I switched to Flutter few years ago, and now making all apps with it (which gives web version out of the box along with native ios/android/linux/windows/mac). Hard to believe people still wasting their time on CSS/JS/HTML for new projects and call hacks like this "amazing".
- yohannparis 5y agoBecause the Web stack is not for making UI apps. Things evolve slowly based on needs, like the `aspect-ratio` property.
- divan 5y agoOf course it's not. Yet it's hard to find non-Electron desktop apps nowadays.
- jrochkind1 5y agoI really want to use aspect-ratio, but a recent thread on HN, that now I can't find, has me worried that I shouldn't be counting on CSS until its been supported by the browsers for a couple years. The recent thread was about all the reasons that even "evergreen" browsers might still have plenty of people using old versions, and was on a thread about a Chromebox still in use that could not have it's version of Chrome updated.
- dbbk 5y agoYou should generally make these decisions based on the usage stats of your own visitors. Caniuse.com for example lets you import Google Analytics data.
- jrochkind1 5y agoThat makes sense, but I'm still cautious of just automatically doing it. 1) it can be a bit circular; if the site doesn't work with a browser, people on that browser are probably not going to spend much time there 2) Depending on what you are doing and your goals/mission (I generally work in academic/non-profit/public sector), you may have a mission that encourages you to be accessible to people on "old technology" regardless of the % of visitors. I've been thinking maybe a standard of 1-2 year old version of popular "evergreen" browsers might make more sense, than what many people default to "latest version". Which would put aspect-ratio not quite over the finish line, alas.
- gbromios 5y agothis is great, but what sticks out to me is how quickly this seems to have been rolled out. Unless I'm misreading something, this went from first public draft [1] to full support [2] in less than two years? Maybe I just haven't been paying attention to the rate new CSS features, but from my perspective this totally just dropped out of the sky. Here's hoping we can continue this pace. [1] https://www.w3.org/TR/2020/WD-css-sizing-4-20200526 https://www.w3.org/TR/2020/WD-css-sizing-4-20200526 [2] https://caniuse.com/?search=aspect-ratio https://caniuse.com/?search=aspect-ratio