惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
PCI Perspectives
PCI Perspectives
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
Google Online Security Blog
Google Online Security Blog
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
The GitHub Blog
The GitHub Blog
S
Secure Thoughts
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
WordPress大学
WordPress大学
SecWiki News
SecWiki News
B
Blog
小众软件
小众软件
Hacker News - Newest:
Hacker News - Newest: "LLM"
Webroot Blog
Webroot Blog
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
L
LINUX DO - 热门话题
Recent Commits to openclaw:main
Recent Commits to openclaw:main
酷 壳 – CoolShell
酷 壳 – CoolShell
IT之家
IT之家
The Cloudflare Blog
Google DeepMind News
Google DeepMind News
Know Your Adversary
Know Your Adversary
Y
Y Combinator Blog
F
Fortinet All Blogs
W
WeLiveSecurity
博客园 - Franky
MongoDB | Blog
MongoDB | Blog
Last Week in AI
Last Week in AI
The Last Watchdog
The Last Watchdog
S
Schneier on Security
爱范儿
爱范儿
V
V2EX - 技术
L
LINUX DO - 最新话题
月光博客
月光博客
博客园 - 【当耐特】
Latest news
Latest news
阮一峰的网络日志
阮一峰的网络日志
博客园 - 司徒正美
U
Unit 42
Schneier on Security
Schneier on Security
E
Exploit-DB.com RSS Feed
J
Java Code Geeks
Cyberwarzone
Cyberwarzone
T
The Blog of Author Tim Ferriss
TaoSecurity Blog
TaoSecurity Blog
博客园 - 叶小钗
T
Troy Hunt's Blog
大猫的无限游戏
大猫的无限游戏
AI
AI
Security Latest
Security Latest

Matthias Ott

Hello Again, World This, Still Not for Everyone The Shape of Friction WeissKlang L1 – Punching Above Its Weight Continvoucly Morged Value Webspace Invaders To Affinity and Beyond The Mystery of Storytelling Amateurs! Echoes of Connection Linear() Is Not (That) Linear View Transitions: The Smooth Parts Adding AVIF and WebP Support to My Craft CMS Site Challenge Acoustic Room Treatment and Building Sound Panels, Part 1: Planning Play On Overshoot The HTML Output Element Listening Closely Compressed Fluid Typography The Lifeblood of the Web What Could Go Wrong? That’s My Rank Making Space CSS :is() :where() the Magic Happens Visual Regression Testing for External URLs With Playwright Jane Goodall’s Famous Last Words European Tech Alternatives 🇪🇺 Independent Type Foundry Advent Calendar – Day 24: NaN Independent Type Foundry Advent Calendar – Day 23: Typotheque Independent Type Foundry Advent Calendar – Day 22: 205TF Independent Type Foundry Advent Calendar – Day 21: HvD Fonts Independent Type Foundry Advent Calendar – Day 20: Frere-Jones Type Independent Type Foundry Advent Calendar – Day 19: Fontwerk Independent Type Foundry Advent Calendar – Day 18: Vectro Independent Type Foundry Advent Calendar – Day 17: Studio René Bieder Independent Type Foundry Advent Calendar – Day 16: R-Typography Independent Type Foundry Advent Calendar – Day 15: David Jonathan Ross Independent Type Foundry Advent Calendar – Day 14: Interval Type Independent Type Foundry Advent Calendar – Day 13: Newglyph Independent Type Foundry Advent Calendar – Day 12: Swiss Typefaces Independent Type Foundry Advent Calendar – Day 11: Sharp Type Independent Type Foundry Advent Calendar – Day 10: Colophon Foundry Independent Type Foundry Advent Calendar – Day 9: Commercial Type Independent Type Foundry Advent Calendar – Day 8: Letters from Sweden Independent Type Foundry Advent Calendar – Day 7: Lineto Independent Type Foundry Advent Calendar – Day 6: Ohno Type Company Independent Type Foundry Advent Calendar – Day 5: Milieu Grotesque Independent Type Foundry Advent Calendar – Day 4: TypeMates Independent Type Foundry Advent Calendar – Day 3: Klim Type Foundry Independent Type Foundry Advent Calendar – Day 2: Dinamo Independent Type Foundry Advent Calendar – Day 1: Grilli Type The Independent Type Foundry Advent Calendar 2022 A Conversation With ChatGPT ChatGPT, please explain websites in the words of William Shakespeare Transient Frameworks Leaving Twitter Behind Converting Your Twitter Archive to Markdown The Wrong Question It Wasn’t Written Syndicating Posts from Your Personal Website to Twitter and Mastodon Suspension None of Your Business Doing Our Part Patch That Package Brain Dump Generating Accessibility Test Results for a Whole Website With Evaluatory The CSS Cascade, a Deep Dive Updates About Updates How to Delete Your Commit History in Git Unblocking Your Writing Blocks, Part 2: I’m Not an Expert nor a “Thought Leader” Connections No Wrong Notes Better Options Design Debt Finite and Infinite Games Don’t Assume, Validate. Necessity Is the Ultimate Teacher One Egg Go Deep There Is No Secret Code Balancing Risk Blue Eyes, Brown Eyes The Shortcut Boomerang My RSS Feed Collection of Personal Websites Frequency The Illusion of Control The Decisions Journey Write It Down Nownownow Into the Personal-Website-Verse Considering the Opposite What is it for? Unlimited Bowling. Never done. We Are Team Internet. We Need to Save #NetNeutrality. Progressive Search Data loss (also) by JavaScript Books I Will Definitely Maybe Read in 2017 Starting to Write Notes
Aspect Ratio in CSS: Hacks and a New Property
Matthias Ott · 2020-09-05 · via Matthias Ott

Layout on the Web is all about flexibility. That elements adjust their dimensions to the size of their content, be it texts of varying length or images of different sizes, is a welcome feature, especially in times of Responsive Web Design because this flexibility makes building responsive layouts possible in the first place. Sometimes, though, we need an element with a fixed aspect ratio, for example, if we want to embed a video via an iframe or to show images cropped to a fixed aspect ratio, regardless of their original dimensions. In such cases, the infamous vertical padding hack has become our method of choice. It goes a little something like this:

.aspect-ratio-hack {
  position: relative;
  height: 0;
  padding-top: 56.25%;
    
  .inner {
	  position: absolute;
	  top: 0;
	  right: 0;
	  bottom: 0;
	  left: 0;
  }
}

In CSS, you can’t simply set the height of an element in relation to its width. Yet this would be needed to define an aspect ratio for an element. If you set a value for vertical padding in percent, though, it is always calculated with respect to the current width of the element. And that is exactly what we harness with the vertical padding hack: If we want to maintain an aspect ratio of 16:9, for example, we set the padding-top of the outer container to 56.25% (because 100 % / 16 * 9 = 56.25 %) and the height to 0. Now, our container has the right dimensions but because its height is 0, the content wouldn’t be visible. That’s why we use an .inner element to wrap the content and set its position to absolute. The inner element is pulled out of the document flow and we can now set its top, right, bottom, and left positions to 0 so that it completely fills the space of its parent. The outer element has itself a position of relative. This way, we make sure that the absolute position of the inner element is calculated based on the outer element because for elements with position: absolute, the browser always looks for the closest ancestor that is not statically positioned to determine the position.

Two rectangles showing the aspect ratio hack in action

And that’s it! Our element has a fixed aspect ratio. But as clever as this technique is, it still feels like a dirty hack. We are using padding to set the height of an element with height: 0 and are combining it with an additional wrapper that is absolutely positioned. If that is not a layout hack, I don’t know what is.

Over time, people came up with many variations of the vertical padding hack. But although setting the aspect ratio with data-attributes or custom properties (CSS variables) might be a bit more modern approaches, all those solutions are still hacks.

A Slightly Better Hack #

The most sophisticated version of the padding hack might be what Chris Coyier calls the pseudo-element tactic. In the example above, we have set a fixed aspect ratio. But what if there is too much content inside our element, for example, a truckload of text that might fit into the container on larger screens but will overflow on smaller viewports?

Text is overflowing a box of an aspect ratio of 16 by 9

Because we defined a fixed height, our container can’t grow accordingly. Essentially, what we want to achieve instead is something like a min-aspect-ratio. The trick is to apply the padding to a pseudo-element instead of the element itself. This way, the content can still make our element grow but it has at least the height of the pseudo-element – which we float out of the way:

.aspect-ratio-hack-better {
  &::before {
    content: "";
    padding-top: 56.25%;
    float: left;
  }
  
  &::after {
    clear: left;
    content: " ";
    display: table;
  }
}
The text is now contained within the outer box. A dotted line indicates where the aspect ratio ends.

The vertical padding hack with pseudo-element tactic: The pseudo-element defines the min-height according to the aspect ratio but the element can still grow with its content.

A Look Into The Future: aspect-ratio #

But wouldn’t it be nice – and more intuitive for beginners – to have a way to set the aspect ratio in CSS without any hacks? This is exactly what the CSS Working Group proposed last year: a new CSS property named aspect-ratio. The property, which still has to be implemented by browser vendors, will let you define a simple ratio like 16 / 9.

.aspect-ratio {
  aspect-ratio: 16 / 9;
}

If you want to play around with aspect-ratio, you can do so in Chrome Canary with the Experimental Web Platform Features flag set. And as Chris Coyier notes in his excellent article on CSS-Tricks, aspect-ratio does support overflowing content and can be overridden by setting min- and max-width or height, respectively, for example. aspect-ratio will also let an element expand if it breaks out of the aspect ratio, but you can also constrain the height to the aspect ratio by adding min-height: 0.

Setting the aspect ratio of an element will remain a hack for the foreseeable future, but with the aspect-ratio property, a much more accessible and straightforward solution is just around the corner.

In the meantime, here is a Codepen for you to tinker with.

See the Pen Apect Ratio Playground by Matthias Ott (@matthiasott) on CodePen.

-

This is the 56th post of my 100 days of writing series. You can find a list of all posts here.

~

6 Webmentions

2 Likes

ⓘ Webmentions are a way to notify other websites when you link to them, and to receive notifications when others link to you. Learn more about Webmentions.